'Node/Express I can't get the header set up in my route
I have a backend that uses Node and the Express framework and a frontend in React. The code is in Typescript.
My backend uses the elastic search client to fetch the data but I don't think that's where my problem lies.
I need to retrieve a parameter that I fetch from the backend via the http header of my response in my frontend.
To do this I used these two functions from the Express doc http://expressjs.com/en/4x/api.html#res.set and http://expressjs.com/en/4x/api.html#res.json
So I wrote the following code for my route:
searchRouter.get('/search', (asyncHandler(async (req, res) => {
const response = await client.search<HitResult>({
index: my-index,
scroll: "1m",
body: {
My elastic request
}
});
res.set('data_to_send',response.body.data_to_send);
console.log('is there a hearder? ', res.headersSent) //always return false
res.json(response);
})));
But the header does not change with this method. So I tried to create an asynchronous function to fill my header with the following code:
async function buildHeader(response: express.Response<any, Record<string, any>>, headerName: string, headerValue: string | undefined): Promise<any> {
response.header(headerName,headerValue);
}
searchRouter.get('/search', (asyncHandler(async (req, res) => {
const response = await client.search<HitResult>({
index: my-index,
scroll: "1m",
body: {
My elastic request
}
});
await buildHeader(res, 'data_to_send', response.body.data_to_send);
console.log('is there a hearder? ', res.headersSent) //always return false
res.json(response);
})));
Whatever I do the header does not change and keeps its basic form, the following one:
content-length: "50643"
content-type: "application/json; charset=utf-8"
Does anyone see what I'm doing wrong and could help me, that would save me. Thanks in advance :)
Solution 1:[1]
As Itai pointed out to me, my problem came from the middleware I was using, CORS. By adding in the options of this middleware the two following fields:
'allowedHeaders': ['data_to_send'],
'exposedHeaders': ['data_to_send'],
Everything works as expected. For more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vincent |