Let us say you have a React frontend and trying to POST a form to your Node backend. After you hit that submit button, you will be hit with an error in the console.
You basically do not have access to that backend, so we will use CORS to enable it.
First thing is always to install the package
npm install cors
Then we would have to require 'cors' and allow our server to use it.
const express = require('express')
const cors = require('cors')
const app = express()
app.use('cors')
Leaving it like this would allow anything to access your server. This is obviously not good since we do not want anything but our frontend to find access to our backend.
A way to access a single endpoint would be
const express = require('express')
const cors = require('cors')
const app = express()
app.get('/products/:id', cors(), function(req, res, next)) {
res.json({msg: 'CORS enabled for this endpoint'})
}
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
If you wish to whitelist a website
const express = require('express')
const cors = require('cors')
const app = express()
const whitelist = {
origin: 'localhost:3000'
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only localhost:3000'})
})
Link
to cors documentation
Top comments (2)
I am not that proficient with
express
but I am pretty sure a string is invalid and if it isn't it probably isn't a good practice.Hey, I see a typo in there.
Should be -