1

I am working on a NodeJS+Express application. I am not able to receive an incoming header.

I am expecting a header named 'authKey' from another service. But I'm getting undefined when I print this. Refer the code below:

const authKey = req.header('auth-key');
console.log(`authKey:${authKey}`);

Output:

authKey:undefined

I tried using npm cors package too, but the result was the same.

  • It will come inside request or in middle. It will not seen anywhere else. Try this: ``` app.get('/', (req, res) => { req.header('auth-key') }) ``` – Shubham Verma Aug 22 '20 at 13:44
  • Tried this too @ShubhamVerma, didn't work. Is it possible that this particular key is getting blocked by the firewall of my company? Because, there are various other keys like host, user-agent, content-type that are available in the req.headers. – Ishan Khanna Aug 22 '20 at 17:56
  • change `header` to `headers and it will work fine – MohamadrezaRahimianGolkhandani Aug 23 '20 at 06:40

2 Answers2

0

there are 2 ways to get a header from the request

  1. console.log(JSON.stringify(req.headers));

this will print all the header key-value present in the request header.

  1. const auth = req.headers['auth-key'];

else you can use to get a particular header value. The headers are stored in a JavaScript object, with the header strings as object keys.

Hrishikesh Kale
  • 6,140
  • 4
  • 18
  • 27
0

This is because of Cross Origin Restrictions that all custom headers by default are blocked. 'authKey' is not defined in the list of safe headers.

1. Use one of predefined header:

Refer this for the list of safe headers and their purpose so you can use one of the safe headers to match your purpose. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

2. Use CORS:

Cross-Origin Resource Sharing allows us to relax the security applied to an API.

// nodeJS code
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

Read more about why Cross origin restrictions block custom headers Why does CORS block custom headers by default?

it’s not ”CORS” that’s imposing the default restrictions. Instead those restrictions are just part of the default same-origin policy that browsers follow

  • I faced the same issue, where I was sending a custom header and my nodejs application did not pick it up. both option 1 and 2 solved my purpose. – Ankit Sharma Dec 01 '21 at 05:24