Hayk Safaryan
Hayk Safaryan

Reputation: 2056

Node js Express CORS headers are set but still getting error

In an express app there is a middleware setting the headers like this

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', [
        'Accept',
        'Authorization',
        'Content-Type',
        'Origin',
        'X-Requested-With'
    ].join(', '))
    res.header('Access-Control-Allow-Methods', [
        'DELETE',
        'GET',
        'HEAD',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT'
    ].join(', '))
    next()
})

But when doing a request I still get an error

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Upvotes: 1

Views: 1654

Answers (1)

M Polak
M Polak

Reputation: 877

Try adding the Express CORS package. It should handle adding the CORS headers for you.

Once installed, it would be used like this:

var express = require('express');
var cors = require('cors');
var app = express();

var cors = require('cors');

app.use(cors());

// routes go here

Otherwise, your implementation seems fine as per this example and this one.

Upvotes: 1

Related Questions