无法理解我的节点JS Serveride代码中的CORS的工作

发布于 2025-02-06 17:05:49 字数 926 浏览 1 评论 0原文

以下是我的React应用后端的Server.js代码。

我无法理解下行的工作

app.use(cors(options));

完整代码如下:

const express = require("express");
const app = express();
const cors = require("cors");
let allowed = ["http://localhost:3000", "http://localhost:4000"];
function options(req, res) {
  let tmp;
  let origin = req.header("Origin");
  if (allowed.indexOf(origin) > -1) {
    tmp = {
      origin: true,
      optionSuccessStatus: 200,
    };
  } else {
    tmp = {
      origin: false,
    };
  }
  res(null, tmp);
}

app.use(cors(options));
app.listen(8000, () => {
  console.log("Server running at 8000");
});

app.get("/", (req, res) => {
  res.send("Hi From server hello super");
});

我的怀疑

  1. “选项”是一个具有参数的函数。但是在行app.use(cors(options))中,如何传递参数

  2. res(null,tmp) - >它做了什么。它等效于res.Send(TMP)?

The below is my server.js code of my React app's backend.

I am not able to understand the working of the below line

app.use(cors(options));

The full code is as below:

const express = require("express");
const app = express();
const cors = require("cors");
let allowed = ["http://localhost:3000", "http://localhost:4000"];
function options(req, res) {
  let tmp;
  let origin = req.header("Origin");
  if (allowed.indexOf(origin) > -1) {
    tmp = {
      origin: true,
      optionSuccessStatus: 200,
    };
  } else {
    tmp = {
      origin: false,
    };
  }
  res(null, tmp);
}

app.use(cors(options));
app.listen(8000, () => {
  console.log("Server running at 8000");
});

app.get("/", (req, res) => {
  res.send("Hi From server hello super");
});

My doubt

  1. The "options" is a function which has arguments . But in the line app.use(cors(options)), how the arguments are passed

  2. res(null,tmp) -> what does it do. Is it equivalent to res.send(tmp)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单 2025-02-13 17:05:49

这是在使用 express-cors middleware 一些文档描述具有options是一个函数意味着什么。

具体来说,中间件调用options函数,因为正在处理请求以确定对指定字段的影响,例如onect methot , 一句,您的代码具有此字段的错别字 - 它缺少s)等。

optionssuccessstatus(顺便说 只是一个回调,可以让其余中间件和其他中间件继续正常执行。

This is using the Express-CORS middleware which has some documentation describing what it means to have options be a function.

Specifically, the options function is called by the middleware as the request is being processed to determine the impact on the specified fields like origin, method, optionsSuccessStatus (by the way, your code has a typo for this field—its missing an s), etc.

As the documentation shows, res is just a callback that lets the rest of the middleware and other middlewares continue normal execution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文