Sachin Shah
Sachin Shah

Reputation: 4533

How to allow CORS in hapi.js

I'm new to Hapi.js and I have design one login API. I got proper payload data from postman but when I call the same API from my angular app, I didn't get data. Even in the network tab, it shows failed status.

After some RND I found the CORS issue and I have set CORS this way.

const server = Hapi.server({
    port: 3000,
    host: '192.168.1.13',        
    "routes": {
        "cors": {
            "origin": ["Access-Control-Allow-Origin","192.168.1.13:4200"],
            "headers": ["Accept", "Content-Type"],
            "additionalHeaders": ["X-Requested-With"]
        }
    }
});

I used this link for refrence.

My node server is running on 3000 port and angular app on 4200.

Error message:

Access to XMLHttpRequest at 'http://192.168.1.13:3000/login' from origin 'http://192.168.1.13:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Upvotes: 1

Views: 10561

Answers (1)

marcodt89
marcodt89

Reputation: 411

Try to write it like that without the "Access-Control-Allow-Origin" if did not do already. It may be the source of the issue:

const server = Hapi.server({
port: 3000,
host: '192.168.1.13',        
"routes": {
    "cors": {
        "origin": ["http://192.168.1.13:4200"],
        "headers": ["Accept", "Content-Type"],
        "additionalHeaders": ["X-Requested-With"]
    }
}
});

If even this does not work, try this just to be sure that problem is not elsewhere:

const server = Hapi.server({
port: 3000,
host: '192.168.1.13',        
"routes": {
    "cors": true
}
});

Upvotes: 7

Related Questions