拦截器未正确发送标头

3
我遇到了一个使用Angular 5进行HTTP请求的问题。我需要发送一个包含令牌(jwt)的头文件,所以我编写了一个拦截器,在用户登录后能够添加令牌。 问题在于,这个头文件并不是作为独立的头文件发送的,当它被发送时,值是丢失的。
以下是我找到并尝试使用的示例代码:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable <HttpEvent<any>> {

  console.log("intercepted request ... ");

  // Clone the request to add the new header.
  const authReq = req.clone({ headers: req.headers.set("headerName", "headerValue") });

  console.log("Sending request with new header now ...");
  console.log(authReq.headers);

  //send the newly created request
  return next.handle(authReq)
    .catch((error, caught) => {
      //intercept the respons error and displace it to the console
      console.log("Error Occurred");
      console.log(error);
      //return the error to the method that called it
      return Observable.throw(error);
    }) as any;
}

这是头部信息的发送方式:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: Array(1), headers: Map(0), lazyInit: HttpHeaders}
headers:Map(1) {"headername" => Array(1)}
lazyInit:null
lazyUpdate:null
normalizedNames
:Map(1)
size:(...)
__proto__:Map
[[Entries]]:Array(1)
0:{"headername" => "headerName"}
key:"headername"
value:"headerName"
length:1
__proto__:Object

这是服务器接收到的内容:

'access-control-request-headers': 'headername',
accept: '*/*',
'accept-encoding':

您可以给予建议吗?我做错了什么?

编辑

我发现问题在于中间件,但我找不到错误所在。

中间件负责验证用户是否有令牌。问题在于当发送请求时,包含令牌的标头未被正确发送。

这是我的中间件:

router.use(function(req,res,next){
    // do logging
    console.log('Somebody just came to our app!');
    console.log(req.headers);
    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, superSecret, function(err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next(); // make sure we go to the next routes and don't stop here
            }
        });

    } else {

        // if there is no token
        // return an HTTP response of 403 (access forbidden) and an error message
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });

    }
});

我也使用拦截器,就像我之前提到的那样,只是有一个小改变:
const authReq = req.clone({ headers: req.headers.set('x-access-token', token) });

现在,从前端发送的每个需要验证的请求都是这样的:
Somebody just came to our app!
{ host: 'localhost:3000',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'he,he-IL;q=0.8,en-US;q=0.5,en;q=0.3',
  'accept-encoding': 'gzip, deflate',
  'access-control-request-method': 'GET',
  'access-control-request-headers': 'x-access-token',
  origin: 'http://localhost:4200',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache' }
OPTIONS /api/todos 403 0.930 ms - 48

由于令牌不是标头的一部分,所以我无法验证用户。

我做错了什么?

谢谢

1个回答

1
使用 req.clone() 函数中的 setHeaders
const authReq = req.clone({
    setHeaders: {
        "Authorization": "Bearer " + token
    }
});

1
嗨, 我尝试过这样做,但是我在请求中根本没有得到任何头信息。 - Uriel Parienti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接