how to enable access control allow origin in nodejs
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.
1 | npm install cors |
The enable all CORS Requests config
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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'); }); |
Read Also: install node js ubuntu
Please follow and like us: