标题没有发送角度-5

时间:2018-05-17 06:42:08

标签: angular typescript angular5 angular-services angular-http-interceptors

想要在我的标题中发送授权令牌,尝试了两种不同的方法,但没有一种方法是发送我正在使用的邮件请求:

方法1使用拦截器

   @Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('inter')
    const authHeader = 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbasdImahQHNdwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc';
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
     console.log('intercepted') //got this message in console
    return next.handle(authReq);
  }
}

发布功能

   post(url: String, data: any) {

    return this.http.post(url, data)
      .map(res => res)
      .catch(this.handleError);
  }

通过在服务上打印控制台添加 app.module.ts 我可以在我的控制台上看到该消息

是拦截但是在结果中得到了这个图像:

no headers present

第二种方法非常简单,并且在angular2中使用它但是使用angular5

得到错误
      post(url: String, data: any) {
    const headers = new Headers({'Content-Type': 'application/json'});
    headers.append('Authorization',  'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyasdasdasImhhbXphQHNwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc');
    const options = new RequestOptions({headers});
    return this.http.post(url, data)
      .map(res => res)
      .catch(this.handleError);
  }

收到此错误

response

同样的东西适用于angular2请求选项但不适用于angular5

令牌已正确验证,我通过 POSTMAN

发送请求

2 个答案:

答案 0 :(得分:1)

这是由于CORS的工作原理。浏览器通常不会在 OPTIONS 请求中发送Authorization标头等自定义标头。您需要修复服务器,以便它不会指向 OPTIONS 请求的Authorization标头

答案 1 :(得分:0)

这就是我使用Angular5

的方法
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{ 
  request = request.clone({
    setHeaders: 
    {
      // Adding Authorization header with token stored in local storage
      Authorization: `Bearer ${localStorage.getItem("token")}`
    }
  });

  return next.handle(request).do((event: HttpEvent<any>) =>
  {
    if (event instanceof HttpResponse)
    {
      // You can do something with success response here
    }
  },
  (err: any) =>
  {
    // Do something with errors here
    if (err instanceof HttpErrorResponse)
    {
      // On UNAUTHORIZED, navigate to login page and clear token from local storage
      if (err.status == 401)
      {
        this.router.navigate(["login"]);
        localStorage.clear();
      }
  }
});