I am working with Rest and fetch()
API in browser to POST data with x-api-key
header for authorization.
I tested the API with Postman and curl
and it works just fine:
curl --header "X-API-KEY: my-api-key" -d "my-request-body" -X POST http://localhost:8081/submit
However, It doesn't work with the fetch api. On Chrome:
const response = await fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: {
'x-api-key': 'my-api-key',
'Accept': 'text/plain',
'Content-Type': 'text/plain'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: 'my-request-body'
});
I'm not able the retrieve the API key from request. In my express, router handler:
router.post('/submit', cors(), async (req,res, next) => {
const apiKey = req.header('x-api-key');
console.log(apiKey) // THIS GIVES undefined
});
No x-api-key
header is present in req.headers
object either. Kindly help
CodePudding user response:
I see an issue, not sure if that is what is causing it but you have forgotten your ,
in your fetch headers, maybe try after adding the ,
?
CodePudding user response:
OK. After struggling with it for a bit, I found the issue that was causing it...
The mode: 'no-cors'
was causing it all along. Just set it to mode: 'cors'
instead and you are good to go, for some reason