Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hapi - enabling CORS

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:

enter image description here

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:

enter image description here

like image 395
Patryk Jabłoński Avatar asked Nov 07 '22 05:11

Patryk Jabłoński


1 Answers

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

like image 74
Zardoz Avatar answered Nov 09 '22 23:11

Zardoz