Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Handling CORS Related Issues In An Express Framework Node.js Web Application

TwitterFacebookRedditLinkedInHacker News

Proper cross-origin resource sharing (CORS) configuration is one of those things that is completely necessary when building a RESTful API, but also one of those things that is a total pain in the butt when it comes to prototyping an application. CORS related errors are common when testing a web application where the front-end JavaScript layer exists on a different port or host than the API that it tries to access.

Previously I had written about configuring cross-origin resource sharing via a Golang RESTful API, but this time we’re going to explore the same using Node.js and Express Framework.

Bootstrapping a Node.js with Express Framework Application

Before we jump into the CORS stuff, let’s focus on getting a boilerplate created for our web application. Somewhere on your computer create a new Node.js project. This can be done by executing the following:

npm init -y

The above command will create a package.json file in your current command line path. With the project created, we need to download the Node.js dependencies that we’ll be using. From the command line, execute the following:

npm install express cors --save

In the above command, we’ve specified the express dependency for Express Framework and cors which will be a middleware that we use further in the tutorial. The cors dependency isn’t absolutely necessary as there are two approaches.

Within your project, create an app.js file and include the following code:

const Express = require("express");

const app = Express();

app.get("/", (request, response) => {
    response.send("Hello World");
});

app.listen(3000, () => {
    console.log("Listening on port 3000...");
});

With the boilerplate code in place, we can focus on configuring the cross-origin resource sharing aspect.

Manually Specifying a Cross-Origin Resource Sharing Configuration

The first approach towards configuring CORS does not require any additional middleware that isn’t already found in Express Framework. Within your app.js file, include the following:

app.use(function(request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

What we’re saying in the above code is that we’re accepting requests from all origins, regardless of port or hostname, and we’re accepting a variety of different request headers.

Both the origin and header information can be hardened or softened depending on the needs of your API.

Now let’s take a look at an alternative method that accomplishes the same thing.

Using the CORS Middleware Package for Convenience

When it comes to prototyping, the previously seen approach can be a little overkill. I often find it difficult to remember when trying to whip something up quickly. Instead we can use the cors middleware that we had downloaded previously.

Within the project’s app.js file, modify your code to look like the following:

const Express = require("express");
const Cors = require("cors");

const app = Express();

app.use(Cors());

app.get("/", (request, response) => {
    response.send("Hello World");
});

app.listen(3000, () => {
    console.log("Listening on port 3000...");
});

Notice that we’ve imported the package dependency and told Express to use it. This is a significantly reduced effort in comparison to the previous option.

Per the documentation for the middleware, it can be configured to be more strict, just like the other approach.

Conclusion

You just saw two different approaches to working with cross-origin resource sharing (CORS) in a Node.js with Express Framework application. You can create your own middleware and specify the allowed headers and origins or you can use a package recommended by the creators of Express.

Another option to bypassing CORS is to do it from a browser level, as demonstrated in a previous article that I had written.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.