使用Interceptor

时间:2018-01-19 23:51:37

标签: javascript angularjs node.js express interceptor

我使用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 个答案:

答案 0 :(得分:1)

setHeaders功能中使用req.clone()

const authReq = req.clone({
    setHeaders: {
        "Authorization": "Bearer " + token
    }
});