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.
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.
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.
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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With