Configuring CORS with Express.js

Configuring CORS with Express.js

The term "cross-origin resource sharing" (CORS) is used to describe a process by which we can permit or forbid requests from other domains for otherwise protected resources on a web page that are being provided from a given domain. We have a server running on localhost:8080, and in the next few chapters, we'll set up an Angular CLI development server on a different port. In order for our Angular frontend to make requests, we need to configure CORS in our Express.js server, as different ports on localhost are treated as different origins. The good news is that Express.js makes it simple to set up CORS. To install the cors module, navigate to the backend's root folder and enter the following command into the terminal:

npm install cors

You should now access the src/index.ts file and import the cors module:

import cors from 'cors'; 

Then, underneath the line that initiated the Express.js application instance, add the following:

app.use(cors()); 

This is the default setting for CORS in our Express.js server, which means that data requests from other domains are permitted. For more options on how to configure CORS while keeping your server resources secure from unintended users, you can check out the module's documentation at https://expressjs.com/en/resources/middleware/cors.html.

As a recap, the previous tutorials marked the beginning of work on the backend application that will provide access to the GraphQL API. Since our code base will house both the backend and client applications, we decided to use the monorepo methodology and set up a project in lerna to do so.

We set up Apollo Server for GraphQL and TypeScript to work with Express.js. After that, we set up Apollo Server with mocking and developed a basic GraphQL schema for our community app.

With the help of mocking, we were able to run a GraphQL server with only a schema and without implementing the resolvers. This is a great addition because it allows us to test the GraphQL API without having to set up and maintain an entire API server. Without having to wait for the backend development to be completed, the frontend developer or team can jump right in and begin working on features that require data fetching from the server.

Then, we queried our Apollo Server from Apollo Studio, and got back information that matched the schema types we had specified. Finally, we configured CORS in our Express/Apollo Server to allow our frontend application to send requests without being blocked by the same-origin policy in web browsers; this is necessary because our frontend application will be running on a different port at localhost during development.

The development of our backend application, which will expose a fully functional GraphQL API with resolvers that fetch data from a real MySQL database, will continue in the next tutorials.


  • Date: