Cross-origin Resource Sharing (CORS) Problem Encountered in Back-end implementation

Kobayashi
Kobayashi
Aug 31, 2018 · 2 min read

URLs are treated as different domains and not allowed to communicate natively once there is any difference between domain, protocol or port.

A concrete example is as follows:

Table.1 The Cross-origin Example

When implementing back-end solutions for our Assessment 3 task, I have solved the cross-origin problem that the CRUD application with Express and MongoDB is using different port than our React application.

It is a common case in web application development that back-end APIs and the front-end server are using different ports. For instance, our React.js development server is running on localhost:3000 while our Express Mongo REST server is running on localhost:3001.

Generally, we will find the error message on the browser console:

XMLHttpRequest cannot load http://localhost:3001. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000' is therefore not allowed access.

To solve it, I defined the CORS response header in the server.js as below:

Pic.1 Defining the Response Header in server.js

The response header specifies whether the resource of the response is allowed to share with the given origin. The asterisk symbol (*) indicates that all origins can access the resource. The “*” can be replaced with a URL indicating that only the specified URL can access the resource.

On the other hand, I installed and saved the Webpack dependency using Yarn instead of npm within our React application (using npm will lead to the run-time error that reads “Cannot read property ‘thisCompilation’ of undefined during npm run build” and we have not figured out why yet). In fact, it is http-proxy-middleware that actually displays its function. I added the following proxy statement in the package.json file:

Pic.2 Defining the Proxy Info in package.json

By doing this, our application is now forwarding “/” requests to port 3000, while redirecting “/api” requests to http://localhost:3001.

After taking measures, the CORS problem which has puzzled me for a while is solved.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade