- vừa được xem lúc

Blog#154: Implementing a CORS sample that supports multiple origins using Node.js and Express

0 0 34

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

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:

  1. Run it on http://localhost:3000 while developing or testing.
  2. After development is finished, it will be used in actual operation at https://xxxxx.com.
  3. 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(","); // We need to support "*" for 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.

Resource

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 528

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 436

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 158

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 149

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 113

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 249