Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Headers not being sent correctly with Interceptor

I am facing an issue with HTTP request using Angular 5. I need to send a header that contains a token (jwt) so I write an interceptor to be able to add the token after user login. The issue is that the header is not being sent as a stand-alone header and when it is being sent, the value is missing.

Here is the example code that I found online and tried to use:

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;
}

this is how the header is being sent :

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

And this is how the server received it:

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

Can you please advise? What am I doing wrong?

EDIT

i found that the issue is witht the middleware and i am not able to find whats wrong.

the middleware is responsible to verify that the user has token. the problem is that when a request is being sent the header that contain the token is not being sent as it should.

this is my middleware :

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.'
        });

    }
});

i am also using interceptor as i mention above,with a minor change :

const authReq = req.clone({ headers: req.headers.set('x-access-token', token) });

now every request that being sent from the fron side that need to be verified looks like this :

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

so i am unable to verifiy user since the the token is not part of the headers.

what am i doing wrong?

Thanks

like image 633
Uriel Parienti Avatar asked May 13 '26 07:05

Uriel Parienti


1 Answers

Use setHeaders in the req.clone() function.

const authReq = req.clone({
    setHeaders: {
        "Authorization": "Bearer " + token
    }
});
like image 116
Brad Avatar answered May 14 '26 21:05

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!