In this article, we will tell you how to enable access control allow origin in node js. When we are connecting a client to a server and retrieve some data from the server, at that time we face this type of error. how to solve this type of error in node js with express. for that, you can follow the below example.

The npm install cors package through we will enable all CORS Requests. so you can install the cors package and see the below example.

npm install cors

The enable all CORS Requests config

server.js

var express = require('express');
var app = express();
var dbConn = require('./config'); 
var bodyParser = require('body-parser');
var cors = require('cors');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
// Retrieve all students data
app.get('/students', function (req, res) {
    dbConn.query('SELECT * FROM students', function (err, results) {
		if(err) {
			throw err;
		} else {
			return res.send({ status: true, data: results});
		}
    });
});
 
 
app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000');
});

The enable cors for a single route config

server.js

var express = require('express');
var app = express();
var dbConn = require('./config'); 
var bodyParser = require('body-parser');
var cors = require('cors');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
// Retrieve all students data
app.get('/students',cors(),function (req, res) {
    dbConn.query('SELECT * FROM students', function (err, results) {
		if(err) {
			throw err;
		} else {
			return res.send({ status: true, data: results});
		}
    });
});
 
 
app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000');
});