Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 491
W.H Avatar asked Nov 29 '17 03:11

W.H


People also ask

How do I enable nodes in CORS?

Enable All CORS Requests If you want to enable CORS for all the request you can simply use the cors middleware before configuring your routes: const express = require('express'); const cors = require('cors'); const app = express(); app.

How do you use CORS in typescript?

Enable CORS We can do that by adding a key "Access-Control-Allow-Origin" on the header of the response. The value of this key is the URL of the application or client you wish to enable CORS for. In our case, it's "http://localhost:3001" or wherever your React app is running. res.


2 Answers

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

like image 84
Sandeep Patel Avatar answered Oct 25 '22 08:10

Sandeep Patel


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.

like image 29
jfriend00 Avatar answered Oct 25 '22 07:10

jfriend00