Fred Coud
Fred Coud

Reputation: 147

CORS and No 'Access-Control-Allow-Origin'

I want to enable access from my server to an extern data. I have this error :

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

I've seen many answers about that thing, mainly unsecured solutions where Chrome protections are disabled, but I want to keep these parameters activated. However if it's only for the resource, it's fine.

So I found this, and I think the "Enable CORS for a Single Route" part could answer my need.

But I have no idea where, in my project, I am supposed to write such code. It can't be in the index.html, since it is in a folder "dist" writen anew each time. So the things I write in dist will be erased when I launch my project. Do I need to make a new file ? A new route ? How do you do that ?

Upvotes: 1

Views: 1541

Answers (3)

sharkdawg
sharkdawg

Reputation: 984

There is no need to use a package for this, just set up a middleware like so

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

As previously mentioned, to limit access to a particular domain change the * to https://whateveryourdomainis.com. If you want allow access to a number of domains then do as @guijob has outlined

Upvotes: 0

guijob
guijob

Reputation: 4488

You can use cors package to easily set these configs. A simple configuration allows all origins:

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

app.use(cors())

you can either allow only specific origins to access your server:

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

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})

Upvotes: 1

Joost Meijer
Joost Meijer

Reputation: 395

The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.


To allow any resource to access your resource, you can specify:

Access-Control-Allow-Origin: *

To allow https://developer.mozilla.org to access your resource, you can specify:

Access-Control-Allow-Origin: https://developer.mozilla.org

Here is the PHP code you are probably looking for:

 header("Access-Control-Allow-Origin: *");

You can find more information about the Access-Control-Allow-Origin on this page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Upvotes: 1

Related Questions