CORS in Nodejs and Express
Understand the Access-Control-Allow-Origin CORS error
We are going to take a look at the error related to CORS which stands for Cross-origin resource sharing.
We will try to generate it and will see how can we solve this error step by step, before starting here is the screenshot on which we are going to work.
So, We are going to make a Nodejs HTTP server.
Create a server via http module that runs on 8000 port number.
Filename: index.js
here is my code :
const http = require('http')
const PORT = 8000
const server = http.createServer()
server.listen(PORT, () => {
console.log(`Server started : http://locahost:${PORT}`)
})
Now make a route of '/' path in the server and we will return JSON data to the client.
const http = require('http')
const PORT = 8000
const server = http.createServer()
server.listen(PORT, () => {
console.log(`Server started : http://locahost:${PORT}`)
})
server.on('request', (req,res) => {
if( req.method === 'GET' && req.url === '/'){
res.end(JSON.stringify({
msg : "this is your precious data"
}));
}
})
Now run your Node app. and access the data from your favorite browser,
I am using chrome. here is output
Now we will fetch data from another origin and we can do it via FETCH API in a browser.
So go the google.com and open your developer tool and send a request to our server using FETCH API.
fetch('http://localhost:8000/').
then(data => data.text()).
then(data => console.log(data))
here is what it looks like in my console
We have successfully reached the resource but the browser denied the response because that resource didn't have the 'Access-Control-Allow-Origin' header so it says No 'Access-Control-Allow-Origin' header is present on the requested resource.
now that we understood the problem here, what we can do is we can set the specific origin to allow our response via Access-Control-Allow-Origin.
so back to our server and we are going add one extra header in the response object.
const http = require('http')
const PORT = 8000
const server = http.createServer()
server.listen(PORT, () => {
console.log(`Server started : http://locahost:${PORT}`)
})
server.on('request', (req,res) => {
if( req.method === 'GET' && req.url === '/'){
res.setHeader('Access-Control-Allow-Origin','https://www.google.com');
res.end(JSON.stringify({
msg : "this is your precious data"
}));
}
})
now re-run your server and try to fetch data from google.com by following the same method.
and woohoo you have successfully solved the error,
but there is still an issue what if you want to allow all the Origin to serve the data
well in that case you just need to set the value as "*".
const http = require('http')
const PORT = 8000
const server = http.createServer()
server.listen(PORT, () => {
console.log(`Server started : http://locahost:${PORT}`)
})
server.on('request', (req,res) => {
if( req.method === 'GET' && req.url === '/'){
res.setHeader('Access-Control-Allow-Origin','*');
res.end(JSON.stringify({
msg : "this is your precious data"
}));
}
})
And Now the problem gets resolved for every origin as well.
Since you have read this far, you should know this as well if you want to allow only 3 or 4 origins to be allowed, you can not just pass the string of array into that header, You should keep an array or an object and whenever server accepts the request just pass the origin manually by checking whether they should be allowed or not.
here is the code: LINK