不了解Express和CORS的功能



这是我在互联网上使用Express和CORS发现的代码:

const express = require('express');
const app = express();
const cors = require('cors');
var corsOptionsDelegate = async (req, callback) => { 
var corsOptions = { origin: false };
try {
...
corsOptions.origin = true;
} catch (err) {
console.log(err);
}
callback(null, corsOptions)
}
app.use(cors(corsOptionsDelegate));

我不知道这个函数callback(null, corsOptions)在这段代码中是如何处理的。

对于简单的服务器,实际上不需要任何函数回调。有一个更简单的方法。

const whiteList = [ "https://myRealBackendUrl-1", "https://myRealBackendUrl-2" ];
// you can also pass a string here instead here instead of array
const corsOptions = {
credentials: true,
origin: process.env.NODE_ENV !== production ? "http://localhost:3000" : whiteList
// if you are in a dev environment, you probably want something like localhost
// if you are in a production environment, for example heroku then your backend 
// url will be something like http://example.herokuapp.com 
// in that case `const whiteList = [ "http://example.herokuapp.com" ];`
};
app.use(cors(corsOptions));

以上代码对于正常用例应该足够了。

至于回调函数,如果你想运行你自己的一些函数,它是。

var corsOptionsDelegate = async (req, callback) => { 
var corsOptions = { origin: false };
try {
// you can do some dynamic check here
// For example: check database for some conditions then allow access
if( myDatabaseSays == true ) corsOptions.origin = true;
else corsOptions.origin = false;
} catch (err) {
console.log(err);
// corsOptions.origin = false;
}
callback(null, corsOptions) // chain it
}

无论如何,阅读文档以获得更多信息[1]: https://expressjs.com/en/resources/middleware/cors.html

这只是一个标准的回调设计模式。这是一篇你可以阅读的文章,但你也应该更多地了解什么是设计模式以及Node.js是如何工作的。这是一个非常基本的问题。

最新更新