Use node JS processing CORS

By Janith Kasun

Crazy technology house

Original text: https://stackabuse.com/handli...

Reprinting without permission is strictly prohibited

introduce

In this paper, we will study how to configure CORS with Express and customize CORS middleware as needed.

What is CORS

CORS is short for "cross domain resource sharing". It is a mechanism that allows or restricts requests for resources from the Web server, depending on where the HTTP request is made.

This policy is used to protect a specific Web server from other websites or domains. Only allowed domains can access files in the server, such as style sheets, images, or scripts.

Suppose you are currently using http://example.com/page1 And you quote from http://image.com/myimage.jpg Pictures, then unless http://image.com Allow and http://example.com Cross domain sharing, otherwise the image will not be available.

Each HTTP request header has a header named origin. It defines the source of the domain request. The information in this header can be used to restrict the reference to resources on your server.

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

For example, if a front-end library such as React or Vue is used during development, the front-end application will run in http://localhost:3000 At the same time, your Express server may be running on other ports, such as http://localhost:2020 . At this time, it is necessary to allow CORS between these servers.

If you see an error like this in the browser console. The problem may be due to CORS restrictions:

If we need to provide public API s and want to control the access and use of certain resources, CORS can play a great role.

In addition, if you want to use your own API s or files on other web pages, you can simply configure CORS to allow you to reference them and keep others out of the way.

Configuring CORS with Express

First create a new project and create the directory structure, and then run npm init with the default settings:

$ mkdir myapp
$ cd myapp
$ npm init -y

Next, install the required modules. We will use express and cors middleware:

$ npm i --save express
$ npm i --save cors

Then, start to create a simple Web program with two routes to demonstrate the working principle of CORS.

First create a file called index JS file, which is used 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');
});

Run server:

$ node index.js

visit http://localhost:2020/ The server should return a JSON message:

{
  "message": "Hello World"
}

visit http://localhost:2020/something You should be able to see:

{
  "message": "Hello something"
}

Enable all CORS requests

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

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

const app = express();

app.use(cors())

......

This allows access to all routes anywhere on the network, if needed. So in this case, each domain can access two routes.

For example, if our server is http://www.example.com Run on and provide content such as pictures, then we allow http://www.differentdomain.com Other domains such as http://www.example.com Conduct citation.

So http://www.differentdomain.com The web page on can use our domain as a source of images:

<img src="http://www.example.com/img/cat.jpg">

Enable CORS for a single route

If only one route is needed, cors can be configured as middleware in one route:

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

This allows any domain to access specific routes. In the current situation, other domains can only access / route. Only with API (in this case http://localhost:2020 )Requests originating in the same domain of can access the /: name route.

If you try to send the request to / from another source, the path will succeed and you will receive Hello World as a response:

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

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

{
    message: 'Hello World'
}

If you access a path other than the root path, for example http://localhost:2020/name Or http://localhost:2020/img/cat.png , the 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));

If you run the code in another Web application, you should see the following error:

Configure CORS with options

You can also configure CORS with custom options. You can configure the allowed HTTP methods as needed, such as GET and POST.

The following is how to allow access to a single domain through the CORS option:

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

app.use(cors(corsOptions));

If you configure a domain name in the source - the server will allow CORS from the configured domain. Therefore, in our example, we can http://localhost:8080 Access the API and prohibit other domains from using it.

If you send a GET request, any path should be accessible because these options are at the application level.

Running the following code will request from http://localhost:8080 Send to 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));

You can see that you are allowed to get information from the program and domain.

You can also configure the allowed HTTP methods as needed:

var corsOptions = {
    origin: 'http://localhost:8080',
    optionsSuccessStatus: 200 // Support for older browsers
    methods: "GET, PUT"
}

app.use(cors(corsOptions));

If from http://localhost:8080 If you send a POST request, the browser will block it because only GET and PUT are supported:

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));

Configuring dynamic CORS source with function

If the configuration does not meet your requirements, you can also create functions to customize CORS.

For example, suppose you want to allow http://something.com and http://example.com yes. CORS sharing jpg files:

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) {
        // Enable CORS for this request
        corsOptions = { origin: true }
    } else {
        // Disable CORS for this request
        corsOptions = { origin: false }
    }
    callback(null, corsOptions)
}

app.use(cors(corsOptionsDelegate));

The callback function accepts two parameters. The first is the error of passing null, and the second is the option of passing {origin: false}. The second parameter can be more options constructed with the request object of Express.

So http://something.com Or http://example.com The Web application on will be able to reference the extension from the server according to the custom configuration jpg picture.

This will successfully reference the resource file:

<img src="http://yourdomain.com/img/cat.jpg">

However, the following files will be blocked:

<img src="http://yourdomain.com/img/cat.png">

Load the list of allowed sources from the data source

You can also use the whitelist stored in the database or any data source to allow CORS:

var corsOptions = {
    origin: function (origin, callback) {
        // Load the list of allowed sources from the database
        // For example: origins = ['http://example.com', 'http//something.com']
        database.loadOrigins((error, origins) => {
            callback(error, origins);
        });
    }
}

app.use(cors(corsOptions));

The first wechat official account of this article: front-end pioneer

Welcome to scan the QR code to follow the official account, and push you fresh front-end technical articles every day

Welcome to continue reading other high praise articles in this column:

Tags: node.js Front-end cors

Posted by domainshuffle on Tue, 10 May 2022 04:22:53 +0300