Angular 7标头未设置

时间:2019-06-21 07:40:45

标签: javascript node.js angular typescript angular-http-interceptors

我正在使用Angular 7,并创建了一个拦截器,在每个请求中都包含auth令牌。

这是我的拦截器代码:

import { Observable } from 'rxjs';

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('authToken');
    if (token) {
      request = request.clone({
        setHeaders: {
          authorization: token
        }
      });
    }
    return next.handle(request);
  }
}

用于验证身份验证令牌的节点api:

const jwt = require('jsonwebtoken');

function verifyToken(req, res, next) {
    var token = req.headers['authorization']; // Coming Undefined 
    if (!token)
        return res.status(403).send({ auth: false, message: 'No token provided.' });
    jwt.verify(token, 'top_secret', function (err, decoded) {
        if (err)
            return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
        // if everything good, save to request for use in other routes
        req.userId = decoded.user.email;
        next();
    });
}

module.exports = verifyToken;

使用Postman命中API时,一切正常,但使用角度代码发送请求时,节点API不会收到标头。

Request header when sent from angular

Request header when sent from Postman

Network Tab Details

Request object sent from browser 这种奇怪行为的可能原因是什么?

3 个答案:

答案 0 :(得分:3)

您显示的屏幕快照是针对CORS所要求的OPTIONS请求的。您需要在nodejs中启用CORS

首先,安装def file = new File('build.gradle') def newConfig = file.text.replace('url "http://some_internal_corporate_repo"', 'url "http://repo.maven.apache.org/maven2/"') file.text = newConfig 模块

cors

然后在您的nodejs后端中使用它

npm install cors

答案 1 :(得分:0)

我在拦截器上遇到了类似的问题,并与授权一起克隆了请求。

我必须添加内容类型并接受标头,然后告诉服务器它是json:

  setHeaders: {
    'Content-Type' : 'application/json; charset=utf-8',
    'Accept'       : 'application/json',
    'Authorization': '' // your token
  }

答案 2 :(得分:0)

尝试那样做

request.clone({
      headers: request.headers.set(
        'Authorization',
        localStorage.getItem('token')
      )
    })