VersifiXion
VersifiXion

Reputation: 2292

Configuring CORS npm package to whitelist some URLs

I have an API here https://api-ofilms.herokuapp.com which send datas to my client https://ofilms.herokuapp.com,

I want to disable CORS for all origin URLs except : - http://localhost:3000 (URL of the client in development), - https://ofilms.herokuapp.com (URL of the client in production),

Because for now, you can see the message on https://api-ofilms.herokuapp.com but I don't want people to access the API,

I tried this before all routes :

const cors = require("cors");

app.use(
  cors({
    origin: ["http://localhost:3000", "https://ofilms.herokuapp.com"],
    credentials: true
  })
);

But I can still see API messages...

Upvotes: 1

Views: 2453

Answers (1)

Andy
Andy

Reputation: 5414

You can try passing in the origin with a callback, like this

Configuring CORS w/ Dynamic Origin

var express = require('express')
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.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Source

Upvotes: 2

Related Questions