XWX
XWX

Reputation: 1997

Expressjs How to enable CORS on just one route?

The code below does not work

app.post('/blah', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD');
    res.status(204).send();
});

Note that I don't want turn on CORS for the whole app.

Upvotes: 10

Views: 9726

Answers (5)

Sandeep Patel
Sandeep Patel

Reputation: 5148

you can use something like this :

var express = require('express')
var cors = require('cors')
var  corsOptions = { origin: 'http://yourapp.com'}
var app = express()

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

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

By default, only 6 response headers are exposed over CORS:

  1. Cache-Control
  2. Content-Language
  3. Content-Type
  4. Expires
  5. Last-Modified
  6. Pragma

If you want to expose other headers, you can use the exposedHeaders option:

 corsOptions = {
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}

Please refer this for more detail on CORS:

More detail on cors

Upvotes: 8

Nicolas
Nicolas

Reputation: 399

Building on Clark Jung's reply, you can use https://github.com/expressjs/cors#enable-cors-for-a-single-route

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

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

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

Upvotes: 0

jfriend00
jfriend00

Reputation: 708046

Posting this as an answer since it turned out to be the issue (per my earlier comment). Depending upon the exact CORS request you are making, then browser may decide that it needs to do a pre-flight of the request. If it does, then you also need to set the custom headers in a matching OPTIONS request.

A number of things can trigger a pre-flight such as custom headers, certain verbs being used, certain auth mechanisms, etc...

There's a description of what types of requests trigger a pre-flight here in these articles:

Using CORS

Cross Origin Resource Sharing

Basically, it's any request that isn't defined as a "simple request" where simple requests only use GET, HEAD and POST and only a small set of custom headers. Anything else and even some values for certain headers will trigger a preflight request where the browser sends an OPTIONS request to the same URL request pre-flight authorization before sending the actual URL.

Upvotes: 3

Kh Jung
Kh Jung

Reputation: 311

Why don't you use https://github.com/expressjs/cors. You can just use like this.

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

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

Or refer to here https://enable-cors.org/server_expressjs.html

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

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

Upvotes: -4

Parker Ziegler
Parker Ziegler

Reputation: 1020

What version of Express are you using? v4 of the API exposes a set() method on res where you can define headers. If passing multiple headers, you pass an object. Try something like this:

res.set({
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD'
});

Documentation.

Upvotes: 1

Related Questions