SoFunction
Updated on 2025-04-08

Detailed explanation of the cors dependency example

`cors` is a middleware used to deal with cross-origin resource sharing (CORS) problems. It is often used in projects that are separated from front and back end.

1. Overview of cross-domain issues

In the browser, for security reasons, the same-origin policy is followed, that is, the browser only allows access to resources with the same origin (protocol, domain name, and port). When a browser initiates a request to a server from a different source, it will be restricted by the browser across domains, resulting in the request being blocked. CORS is a modern cross-domain solution that allows the server to set some fields in the response header to tell the browser that the request is allowed.

1. Install `cors`

# Install using npmnpm install cors

2. Basic use

Apply the `cors` middleware to the entire Express application, which means that all routes allow cross-domain requests. When a client (such as a browser) initiates a request for a `/data` route, the server adds the necessary CORS-related fields to the response header, allowing cross-domain access.

const express = require("express");
const cors = require("cors");
const app = express();
// Use cors middleware(cors());
("/data", (req, res) => {
  ({ message: "This is some data from the server" });
});
const port = 3000;
(port, () => {
  (`Server running on port ${port}`);
});

2. Configuration options

The `cors` middleware provides a variety of configuration options to meet different cross-domain needs.

1. `origin`

Used to specify the origin that allows cross-domain requests. It can be a string, an array, or a function.

// Allow a single sourceconst corsOptions = {
  origin: "",
};
(cors(corsOptions));
// Allow multiple sourcesconst corsOptionsMultiple = {
  origin: ["", ""],
};
(cors(corsOptionsMultiple));
// Use functions to dynamically configure originconst corsOptionsFunction = {
  origin: (origin, callback) => {
    const allowedOrigins = ["", ""];
    if (!origin || (origin)) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
};
(cors(corsOptionsFunction));

2. `methods`

Used to specify allowed HTTP request methods, the default value is `'GET,HEAD,PUT,PATCH,POST,DELETE'`.

const corsOptionsMethods = {
  methods: "GET,POST",
};
(cors(corsOptionsMethods));

3. `allowedHeaders`

Used to specify allowed request headers, by default, the browser will automatically process some common request headers. This option can be used if you need to customize the request header.

const corsOptionsHeaders = {
  allowedHeaders: "Content-Type,Authorization",
};
(cors(corsOptionsHeaders));

4. `exposedHeaders`

Used to specify the response header that allows client access. By default, the browser can only access some simple response headers, and this option can expose more response headers to the client.

const corsOptionsExposed = {
  exposedHeaders: "X-Custom-Header",
};
(cors(corsOptionsExposed));

5. `credentials`

A boolean value indicating whether clients are allowed to carry credentials (such as cookies, HTTP authentication, etc.) in cross-domain requests. The default value is `false`.

const corsOptionsCredentials = {
  credentials: true,
};
(cors(corsOptionsCredentials));

6. Use `cors` for specific routes

In addition to applying `cors` to the entire application, you can also use the `cors` middleware for specific routes.

const express = require("express");
const cors = require("cors");
const app = express();
const corsOptions = {
  origin: "",
};
// Only specific routes are allowed to cross domains("/data", cors(corsOptions), (req, res) => {
  ({ message: "This is some data from the server" });
});
const port = 3000;
(port, () => {
  (`Server running on port ${port}`);
});

This is the end of this article about the detailed explanation of the dependency of the cors dependencies. For more related cors dependencies, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!