The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.
Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.
Implement
When creating a web application using a REST API or front-end framework, it is not uncommon to be troubled by CORS (Cross-Origin Resource Sharing).
CORS is a security restriction for JavaScript in web browsers (front-end), which means that, when using AJAX or other methods to make HTTP requests, only requests from the same origin are allowed and requests from different origins will fail due to the CORS restriction. There are no restrictions for HTTP requests from the back-end, but it only applies to requests from the front-end. For more information, please see here: https://developer.mozilla.org/ja/docs/Web/HTTP/CORS
If the same person is making both the REST API and the front-end web application, or if they know that such requests will come in, they may want to ignore the CORS restriction on the API side. For this, it is possible to set up the API to "allow HTTP requests from a specific origin". Specifically, by specifying the origin (https://allowed-origin.com) to be allowed and returning an HTTP response header of Access-Control-Allow-Origin: https://allowed-origin.com
, the request source will compare this header content to its own origin and process it normally only if it matches (otherwise it will be an error). It is also possible to specify "allow requests from all origins", and in this case it can be realized by returning an exceptional HTTP response header of Access-Control-Allow-Origin: *
.
Now, when developing the front-end side, you may face the following problems:
- Run it on
http://localhost:3000
while developing or testing. - After development is finished, it will be used in actual operation at
https://xxxxx.com
. - A REST API will not work unless CORS settings are configured, which is different in both (1) and (2).
When developing, we use a local host such as http://localhost:3000
to check the code, and when in production, we use an internet host such as https://xxxxx.com
to access it. This is not a particularly unusual case. In order to run the REST API in both development and production environments, it would be convenient to set up CORS (regardless of whether requests from http://localhost:3000
are allowed or not). However, there is a restriction that only one origin (and not even a regular expression other than *
) can be specified in the Access-Control-Allow-Origin header. In other words, it is not possible to specify "allow requests from http://localhost:3000
or https://xxxxx.com
" in the Access-Control-Allow-Origin
header. Is there any way to work around this and make it possible?
One possible way is to specify Access-Control-Allow-Origin: *
during development to allow requests from all origins, but this is also a very vulnerable setting.
I came up with the following method: Prepare an array of allowed origins in advance, and if the request source is included in the allowed origin array, dynamically specify the origin in the Access-Control-Allow-Origin
header and return it. If you make it specifically for the Node.js + Express environment, it looks like this:
// app.js
const express = require("express");
const app = express();
app.use(express.Router());
var settings_cors = "CORS" in process.env ? process.env.CORS : "";
app.all("/*", function (req, res, next) {
if (settings_cors) {
var origin = req.headers.origin;
if (origin) {
var cors = settings_cors.split(" ").join("").split(",");
//. cors = [ "*" ] への対応が必要
if (cors.indexOf("*") > -1) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Vary", "Origin");
} else {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
}
}
}
next();
});
app.get("/ping", function (req, res) {
res.contentType("application/json; charset=utf-8");
res.write(JSON.stringify({ status: true, message: "PONG" }, null, 2));
res.end();
});
var port = process.env.PORT || 8080;
app.listen(port);
console.log("server starting on " + port + " ...");
At startup, specify an array of allowed origins (in this example, "http://localhost:3000
" and "https://xxxxx.herokuapp.com
") as the CORS environment variable, separated by commas.
(sample)$ CORS=http://localhost:3000,https://xxxxx.herokuapp.com node app
This sample (running on port 8080) defines a REST API that responds to a GET /ping request with { status: true, message: 'PONG' }. If the origin of the request is either http://localhost:3000
or https://xxxxx.herokuapp.com
, then CORS restrictions can be bypassed by the Access-Control-Allow-Origin
header.
It looks like we can set up an API server that can be used in test, staging, and production environments without changing the CORS settings.
The sample source code I provided is here: https://github.com/dotnsf/multicors
And Finally
As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!
If you liked this article, please give me a like and subscribe to support me. Thank you. 😊
The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.