DEV Community

Justin Bermudez
Justin Bermudez

Posted on

4 3

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site