405(方法不允许):angular4

时间:2018-04-06 11:30:54

标签: angular rest angular-cli angular4-forms

我尝试使用angular 4将数据发布到后端(我尝试使用angular4应用验证)但是我有这个错误:

enter image description here

我使用扩展谷歌浏览器来解决错误交叉但也有错误 代码服务:

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Data } from '../Data';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import {  RequestOptions, Headers } from '@angular/http';
import {Router} from '@angular/router';


@Injectable()
export class DataServiceService {


  constructor(private http:HttpClient,public router:Router) { }

  Login(data)
  {

    let headers: any = new HttpHeaders();
    headers.append('Content-Type', 'application/json');

    return this.http.post('link api',JSON.stringify(data),{responseType: 'text'})
    .subscribe(res => console.log(res),err => {console.log(err); if (err.status === 401 || err.status === 403) {
            this.router.navigateByUrl(`/login`);
        }});

  }


    public getToken(): string {
    return localStorage.getItem('token');
  }

    public isAuthenticated(): boolean {
    let token = this.getToken();
    if (token === null) return false; else return true;
  }
}

代码组件:

      mySubmit({value,valid}:{value:Data,valid:boolean})
  {
    if (valid === true) { console.log(value);
        this.dataService.Login(value);

     } else console.log('error');
  }

代码拦截器:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http';
  import { Injectable, Injector } from '@angular/core';
  import { Observable } from 'rxjs/Observable';
  import { DataServiceService } from './data-service.service';
  import {Router} from '@angular/router';
  import 'rxjs/add/observable/of';

  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
  //inj:Injector;

    constructor(public inj: Injector,public router:Router) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     const auth = this.inj.get(DataServiceService);
     const authToken = auth.getToken();
     const clonedRequest = req.clone({
              headers: req.headers.set('Authorization', `Bearer ${authToken}`)
              .set('Content-Type', 'application/json')
          });


      return next.handle(req);
    }
  }

现在当发送数据时我有错误405方法不允许,在拦截器中我将application / json添加到Content-Type但也是错误

1 个答案:

答案 0 :(得分:0)

手动添加这些请求标头将导致浏览器在发送POST请求之前发送OPTION请求。您需要通过启用CORS来更改后端服务器配置以允许OPTIONS请求。

您还没有提到您正在使用的后端,但如果它是.net核心,您可以按照此处的说明进行操作:

https://docs.microsoft.com/en-us/aspnet/core/security/cors