无法理解我的节点JS Serveride代码中的CORS的工作
以下是我的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");
});
我的怀疑
“选项”是一个具有参数的函数。但是在行app.use(cors(options))中,如何传递参数
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
The "options" is a function which has arguments . But in the line app.use(cors(options)), how the arguments are passed
res(null,tmp) -> what does it do. Is it equivalent to res.send(tmp)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是在使用 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 likeorigin
,method
,optionsSuccessStatus
(by the way, your code has a typo for this field—its missing ans
), etc.As the documentation shows,
res
is just a callback that lets the rest of the middleware and other middlewares continue normal execution.