1

I am trying to send the token in the headers of an HTTP request from backend to the frontend along with sending my own defined string. However, I am getting an issue. The token is being printed as null on the client-side. I don't know why:

Here's my code:

Node/Express

if (bcrypt.compareSync(passcode, results[0].password))
{
     const token = jwt.sign({id: email}, secret, {expiresIn: 86400 });
     console.log(token);
     if(results[0].userrights == 'full')
       {
          res.setHeader('x-access-token', token);
          res.send("Full Authorization");
       }

    //rest of the code
 }

Angular

this.http.post('http://localhost:3000/api/login', form.value, {responseType: "text", observe: 
                'response'})
  .subscribe(responseData => {
    console.log(responseData);
    console.log(responseData.headers.get('x-access-token'));  //prints null on the console

I have searched quite a bit and found different examples which is making it very confusing. I don't want to use response status rather my own defined string. I have tried different things to print the variable but it still is throwing as null.

  • 1
    what do you have if you print: `console.log(responseData.headers)` ? – Michael Desigaud Mar 24 '21 at 10:59
  • @MichaelDesigaud, the header is showing two entries. content-length and content-type. Length has value of ["18"], content-type has value of "text/html; charset=utf-8" –  Mar 24 '21 at 11:03
  • and in your browser (for example chrome), in the network tab do you see your header `x-access-token` as response header of the request ? – Michael Desigaud Mar 24 '21 at 11:04
  • @MichaelDesigaud, yes, x-access-token: [object Object] –  Mar 24 '21 at 11:08
  • ah `[object Object] ` thats weird, if you replace `res.setHeader('x-access-token', {auth: true, token: token});` by `res.setHeader('x-access-token', token);` in server side ? – Michael Desigaud Mar 24 '21 at 11:10
  • @MichaelDesigaud, now I am getting the x-access-token: "eyJh...xxx" :) –  Mar 24 '21 at 11:12
  • @MichaelDesigaud, but the console is still not printing the token. –  Mar 24 '21 at 11:16
  • there is no uppercase in xhr response headers (network tab), like `X-Access-Token` or something like this ? – Michael Desigaud Mar 24 '21 at 13:07

1 Answers1

0

If you are using a browser extension to allow CORS requests then Access-Control-Expose-Headers should be added to the headers on server side. Please try adding the following line: res.setHeader('Access-Control-Expose-Headers', '*')

Angular2 's Http.post is not returning headers in the response of a POST method invocation

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

Bicskow
  • 16
  • 1
  • thank you so much. It worked. I was adding `app.use(cors())` in my main server program and I thought it would automatically expose the headers for me. Thanks for clearing. :) –  Mar 26 '21 at 04:49