DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Enabling CORS for Node Express Backend

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')
Enter fullscreen mode Exit fullscreen mode

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')
})
Enter fullscreen mode Exit fullscreen mode

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'})
})

Enter fullscreen mode Exit fullscreen mode

Link
to cors documentation

Top comments (2)

Collapse
 
shadowtime2000 profile image
shadowtime2000
const express = require('express')
const cors = require('cors')
const app = express()

app.use('cors')
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Hey, I see a typo in there.

app.use('cors')
Enter fullscreen mode Exit fullscreen mode

Should be -

app.use(cors())
Enter fullscreen mode Exit fullscreen mode