How to use CORS in ExpressJS

In this article, you are going to learn about how to use CORS in ExpressJS. ExpressJS is an open-source backend web application framework for NodeJS….


This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan

In this article, you are going to learn about how to use CORS in ExpressJS.

ExpressJS is an open-source backend web application framework for NodeJS. It is very popular and provides a rich set of features for web development. CORS stands for cross-origin resource sharing. It is a package of NodeJS that provides browser security features by restricting cross-origin HTTP requests. To work with CORS in express you need to install it first and to do so see the below command

npm install cors
// or
npm i cors

In express, it lets you manage an HTTP server’s resources from the same domain but it does not allow other domains. In other words, for example, your backend is hosted in a server and the frontend is in another. To make communication between them CORS comes to play its role. Before using CORS in express, let’s see what happens when we don’t use CORS and try to access data from a different origin.

JavaScript (Same Origin)

const express = require('express');
const app = express();

    const studentInfo = [
    {
        "name" : "Alex",
        "age" : 23
    },
    {
        "name" : "Devid",
        "age" : 25
    },
    {
        "name" : "Alina",
        "age" : 21
    }
];

app.get('/studentInfo', (req, res) =>{
    res.send(studentInfo);
});

const PORT = 8080
app.listen(PORT,()=>{
    console.log(`App is running on Port ${PORT}`)
});

Here, we simply add a get request and our server is running on port 8080. We can get a request by typing 127.0.0.1:8080/studentInfo. Because, this file is being served from the same origin. Now let’s try to access from a different origin and see what happens.

HTML (Different Origin)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Get The Hash Vaule with jQuery</title>
</head>
<body>

 <div class="section">
    <button onclick="getInfo()">Get Info</button>
 </div>

 <script>
     const getInfo = async () =>{
         await fetch("http://localhost:8080/studentInfo")
         .then(req => req.json())
         .then(data => console.log(data))
     }

 </script>
</body>
</html>

Here, we are trying to access studentInfo from a different origin. Let’s see what happens in the console when we have clicked on the Get Info Button.

CORS in ExpressJS

You can see that we are not allowed to get access from a different origin and instead of getting data, we are getting an error. To get data from this domain we need to recognize this to the express and to do so we need to use CORS. See the below code example:

const cors = require('cors');
app.use(cors({
    origin: 'http://127.0.0.1:5500'
}));

Here, in our file, along with those codes we simply require CORS and then set our specific domain so that it can get access to these data. Let’s see the output once again.

CORS in ExpressJS

This time we are being able to access the data because express recognizes this domain. If you need to use multiple domains then you may use an array of the origin or you can simply allow (*) sign to make it public. See the below code example:

app.use(cors({
    origin: '*'
}));

If you use this then any origin may be able to get access. This is a brief idea about CORS and how you can apply it in the express. It is not possible to share all the implementation of CORS in a single article but you may understand the use-case and necessity of using CORS. To get more information you may see the official documentation of CORS.


This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan


Print Share Comment Cite Upload Translate Updates
APA

Md Niaz Rahman Khan | Sciencx (2022-01-21T06:55:09+00:00) How to use CORS in ExpressJS. Retrieved from https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/

MLA
" » How to use CORS in ExpressJS." Md Niaz Rahman Khan | Sciencx - Friday January 21, 2022, https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/
HARVARD
Md Niaz Rahman Khan | Sciencx Friday January 21, 2022 » How to use CORS in ExpressJS., viewed ,<https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/>
VANCOUVER
Md Niaz Rahman Khan | Sciencx - » How to use CORS in ExpressJS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/
CHICAGO
" » How to use CORS in ExpressJS." Md Niaz Rahman Khan | Sciencx - Accessed . https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/
IEEE
" » How to use CORS in ExpressJS." Md Niaz Rahman Khan | Sciencx [Online]. Available: https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/. [Accessed: ]
rf:citation
» How to use CORS in ExpressJS | Md Niaz Rahman Khan | Sciencx | https://www.scien.cx/2022/01/21/how-to-use-cors-in-expressjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.