Skip to main content

Command Palette

Search for a command to run...

node js cors

Published
3 min read
A

Self taught developer working on Angular, Vue, Typescript, Node JS, MongoDB, Express JS, LoopBack API, Laravel, Laravel Lumen, mysql. write packages for angular/vue. Part time youtuber

When we are trying to access the resource from other domain or server we will getting cors errors or according to google search:

What is CORS? ... CORS errors are common in web apps when a cross-origin request is made but the server doesn't return the required headers in the response (is not CORS-enabled): XMLHttpRequest cannot load https://api.example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource

How we handle cors errors in our node/express applications:

First step is to install node.js cors package using below command

npm i --save cors

In case we want to setup cors for all the routes in the application. We need to add cors middleware in app.js file like this:

var cors = require('cors');
var app = express();
app.use(cors());

By default above statement will enable cors for all the requests, in case we want to restrict the request for single domain, we need to add some options and pass into the cors middleware like this:

var cors = require('cors');
var app = express();
var corsOpt = {
  origin: 'your domain url for we want to enable cors',
}
app.use(cors(corsOpt));

How to setup cors for single route in our node/express application. Open your route file and add cors as middleware in that particular route

var cors = require('cors')
var app = express();
var corsOpt = {
  origin: 'your domain url for we want to enable cors',
}
router.get('/users', cors(corsOpt), function(req, res, next) {
  res.json([{
    "id": 1,
    "firstname": "first name",
    "lastname": "last name"
  },{
    "id": 2,
    "firstname": "first name 2",
    "lastname": "last name 2"
  }]);
});

More from this blog

Angular, TypeScript, Vue, Node JS, Express JS, MongoDB, MongoDB Cloud, PHP, Laravel, Slim Framework, Mysql, JavaScript, PWA

24 posts

I'm a Full Stack Developer, Open Source Contributor, Blogger, npm packages developer, Youtuber. My hobbies are Contribution in open source projects, blogging, develop npm packages, part time youtuber