Table of Contents
Introduction
What is CORS
Configuring CORS with Express
Enable all CORS requests
Enable CORS for a single route
#Configuring CORS with options
用函数配置动态 CORS 源
从数据源加载允许的来源列表作
Home Web Front-end JS Tutorial Detailed explanation of how to handle CORS using Node.js

Detailed explanation of how to handle CORS using Node.js

Oct 28, 2020 pm 05:41 PM
cors node.js front end

Detailed explanation of how to handle CORS using Node.js

Video tutorial recommendation: node js tutorial

Introduction

In this article, we will Explore how to configure CORS with Express and customize the CORS middleware as needed.

What is CORS

CORS is the abbreviation of "Cross-domain Resource Sharing". It is a mechanism that allows or restricts requests for resources on a web server, depending on where the HTTP request is made.

This policy is used to protect a specific web server from access by other websites or domains. Only allowed domains can access files on the server, such as stylesheets, images, or scripts.

Assume that you are currently using http://example.com/page1, and you are quoting from http://image.com/myimage.jpg, the image will not be available unless http://image.com allows cross-domain sharing with http://example.com.

There is a header named origin in each HTTP request header. It defines the origin of domain requests. You can use this header information to restrict references to resources on your server.

By default, requests from any other source will be restricted by the browser.

For example, if you use a front-end library such as React or Vue during development, the front-end application will run on http://localhost:3000. At the same time, your Express server May be running on a different port, such as http://localhost:2020. Then you need to allow CORS between these servers.

If you see an error like the one below in the browser console. The problem may lie in CORS limitations:

Detailed explanation of how to handle CORS using Node.js

CORS can play a big role if we need to provide a public API and want to control how certain resources are accessed and used. .

Also, if you want to use your own API or files on other web pages, you can simply configure CORS to allow yourself to be referenced, while keeping others out.

Configuring CORS with Express

First create a new project and create a directory structure, then run it using the default settingsnpm init:

$ mkdir myapp
$ cd myapp
$ npm init -y
Copy after login

Connect Come down and install the required modules. We will use express and cors middleware:

$ npm i --save express
$ npm i --save cors
Copy after login

Then, start creating a simple web program with two routes to demonstrate how CORS works .

First create a file named index.js to act as a Web server and implement several request processing functions:

const express = require('express');
const cors = require('cors');

const app = express();

app.get('/', (req, res) => {
    res.json({
        message: 'Hello World'
    });
});

app.get('/:name', (req, res) => {
    let name = req.params.name;

    res.json({
        message: `Hello ${name}`
    });
});

app.listen(2020, () => {
    console.log('server is listening on port 2020');
});
Copy after login

Run the server:

$ node index.js
Copy after login

Accesshttp://localhost:2020/ The server should return a JSON message:

{
  "message": "Hello World"
}
Copy after login

Visit http://localhost:2020/something and you should be able to see:

{
  "message": "Hello something"
}
Copy after login

Enable all CORS requests

If you want to enable CORS for all requests, you can simply use the cors middleware before configuring the route:

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors())

......
Copy after login

If needed , which allows access to all routes from anywhere on the network. So in this example, each domain has access to two routes.

For example, if our server runs on http://www.example.com and serves content such as images, we allow http://www Other domains such as .differentdomain.com are redirected from http://www.example.com.

So webpages at http://www.differentdomain.com can use our domain as a source for images:

<img  src="/static/imghw/default1.png" data-src="http://www.example.com/img/cat.jpg" class="lazy" alt="Detailed explanation of how to handle CORS using Node.js" >
Copy after login

Enable CORS for a single route

If you only need one of the routes, you can configure cors as middleware in a certain route:

app.get('/', cors(), (req, res) => {
    res.json({
        message: 'Hello World'
    });
});
Copy after login

This will allow any domain to access the specific route. In the current situation, other domains can only access the / route. The /:name route can only be accessed by requests initiated in the same domain as the API (in this case, http://localhost:2020).

If you try another origin sending a request to the / path will succeed and you will receive Hello World in response:

fetch('http://localhost:2020/')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
Copy after login

Run the above code, you will see that the response from the server has been successfully output to the console:

{
    message: 'Hello World'
}
Copy after login

If you access a path other than the root path, such as http://localhost:2020/name or http://localhost:2020/img/cat.png, then this request will be blocked by the browser:

fetch('http://localhost:2020/name/janith')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));
Copy after login

If you run the code in other web applications, you should see the following Error:

Detailed explanation of how to handle CORS using Node.js

#Configuring CORS with options

You can also configure CORS with custom options. Allowed HTTP methods, such as GET and POST, can be configured as needed.

Here's how to allow access to a single domain via CORS options:

var corsOptions = {
    origin: 'http://localhost:8080',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions));
Copy after login

如果你在源中配置域名-服务器将允许来自已配置域的CORS。因此,在我们的例子中,可以从 http://localhost:8080 访问该API,并禁止其他域使用。

如果发送一个 GET 请求,则任何路径都应该可以访问,因为这些选项是在应用在程序级别上的。

运行下面的代码将请求从 http://localhost:8080 发送到 http://localhost:2020

//
fetch('http://localhost:2020/')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

//
fetch('http://localhost:2020/name/janith')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));
Copy after login

可以看到被允许从该程序和域中获取信息。

还可以根据需要配置允许的 HTTP 方法:

var corsOptions = {
    origin: 'http://localhost:8080',
    optionsSuccessStatus: 200 // 对于旧版浏览器的支持
    methods: "GET, PUT"
}

app.use(cors(corsOptions));
Copy after login

如果从 http://localhost:8080 发送POST请求,则浏览器将会阻止它,因为仅支持 GET 和 PUT:

fetch('http://localhost:2020', {
  method: 'POST',
  body: JSON.stringify({name: "janith"}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Copy after login

用函数配置动态 CORS 源

如果配置不满足你的要求,也可以创建函数来定制 CORS。

例如假设要允许 http://something.com 和 http://example.com 对 .jpg  文件进行CORS共享:

const allowlist = ['http://something.com', 'http://example.com'];

    const corsOptionsDelegate = (req, callback) => {
    let corsOptions;

    let isDomainAllowed = whitelist.indexOf(req.header('Origin')) !== -1;
    let isExtensionAllowed = req.path.endsWith('.jpg');

    if (isDomainAllowed && isExtensionAllowed) {
        // 为此请求启用 CORS
        corsOptions = { origin: true }
    } else {
        // 为此请求禁用 CORS
        corsOptions = { origin: false }
    }
    callback(null, corsOptions)
}

app.use(cors(corsOptionsDelegate));
Copy after login

回调函数接受两个参数,第一个是传递 null 的错误,第二个是传递  { origin: false } 的选项。第二个参数可以是用 Express 的 request 对象构造的更多选项。

所以 http://something.comhttp://example.com 上的 Web 应用将能够按照自定义配置从服务器引用扩展名为 .jpg 的图片。

这样可以成功引用资源文件:

<img  src="/static/imghw/default1.png" data-src="http://yourdomain.com/img/cat.jpg" class="lazy" alt="Detailed explanation of how to handle CORS using Node.js" >
Copy after login

但是下面的文件将会被阻止:

<img  src="/static/imghw/default1.png" data-src="http://yourdomain.com/img/cat.png" class="lazy" alt="Detailed explanation of how to handle CORS using Node.js" >
Copy after login

从数据源加载允许的来源列表作

还可以用保存在数据库中的白名单列表或任何一种数据源来允许 CORS:

var corsOptions = {
    origin: function (origin, callback) {
        // 从数据库加载允许的来源列表
        // 例如:origins = ['http://example.com', 'http//something.com']
        database.loadOrigins((error, origins) => {
            callback(error, origins);
        });
    }
}

app.use(cors(corsOptions));
Copy after login

原文:https://stackabuse.com/handling-cors-with-node-js/

作者:Janith Kasun

更多编程相关知识,可访问:编程教学!!

The above is the detailed content of Detailed explanation of how to handle CORS using Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

How to use Go language for front-end development? How to use Go language for front-end development? Jun 10, 2023 pm 05:00 PM

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Can golang be used as front-end? Can golang be used as front-end? Jun 06, 2023 am 09:19 AM

Golang can be used as a front-end. Golang is a very versatile programming language that can be used to develop different types of applications, including front-end applications. By using Golang to write the front-end, you can get rid of a series of problems caused by languages ​​​​such as JavaScript. For example, problems such as poor type safety, low performance, and difficult to maintain code.

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

How to use CORS cross-domain request in PHP-Slim framework? How to use CORS cross-domain request in PHP-Slim framework? Jun 03, 2023 am 08:10 AM

In web development, cross-domain requests are a common problem. This is because browsers have strict restrictions on requests between different domain names. For example, website A's front-end code cannot send requests directly to website B's API unless website B allows cross-domain requests. In order to solve this problem, CORS (Cross-Origin Resource Sharing) technology emerged. This article will introduce how to use CORS cross-domain requests in the PHP-Slim framework. 1. What is CORSCORS? It is a mechanism that adds some amounts to the corresponding HTTP header.

What is a front-end modular ESM? What is a front-end modular ESM? Feb 25, 2024 am 11:48 AM

What is front-end ESM? Specific code examples are required. In front-end development, ESM refers to ECMAScriptModules, a modular development method based on the ECMAScript specification. ESM brings many benefits, such as better code organization, isolation between modules, and reusability. This article will introduce the basic concepts and usage of ESM and provide some specific code examples. The basic concept of ESM In ESM, we can divide the code into multiple modules, and each module exposes some interfaces for other modules to

See all articles