I am writing BE application using Node JS and Hapi (v17). While the server is running and I try to call an endpoint using POST
method I keep receiving an error message:
Failed to load http://localhost:8001/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I wanted to enable CORS
on the server site, but nothing works for me.
here is how I enable CORS on the server site:
const hapi = require('hapi')
const server = hapi.server({
port: 8001,
host: 'localhost',
routes: {
cors: true
}
})
I was also trying to enable cors for the specific route but this also has no effect:
server.route({
method: 'POST',
path: '/login',
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
handler: async (request, reply) => {
return User.login(request, reply)
}
})
Does anyone know what should I do to enable CORS and get rid of the problem?
Additionally, there is a screenshot from the browser's network tab:
EDIT:
I have added route that handles OPTIONS
method and now I have another issue.
Failed to load http://localhost:8001/login: Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.
And here is how things look like in the network tab:
cors: {
origin: [
'*'
],
headers: ["Access-Control-Allow-Headers", "Access-Control-Allow-Origin","Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"],
additionalHeaders: ["Access-Control-Allow-Headers: Origin, Content-Type, x-ms-request-id , Authorization"],
credentials: true
}
You should also probably define a qualified domain, instead of just * wildcard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With