【问题标题】:Headers not sent angular-5标头未发送 angular-5
【发布时间】:2018-10-27 08:06:42
【问题描述】:

想在我的标头中发送授权令牌,尝试了两种不同的方法,但没有一个是发送我正在用于发布请求的令牌:

方法一使用拦截器

   @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 我可以在控制台上看到消息

是被截获但在结果中得到了这张图片:

第二种方法非常简单,在 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);
  }

收到此错误

同样的事情适用于 angular2 请求选项,但不适用于 angular5

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

发送请求

【问题讨论】:

  • This 是您所需要的。
  • @NilayVishwakarma 对我来说没什么特别的,我已经尝试过 cors

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


【解决方案1】:

这就是我使用 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();
      }
  }
});

【讨论】:

    【解决方案2】:

    这取决于 CORS 的工作方式。浏览器通常不会在 OPTIONS 请求中发送自定义标头,例如 Authorization 标头。您需要修复您的服务器,使其不期望 OPTIONS 请求的 Authorization 标头

    【讨论】:

    • 我已经在 chrome 和服务器端启用了 cors
    • 问题是您不应该期望授权标头存在于 OPTIONS 请求中
    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多