如何在KeystoneJSv4中设置CORS



我有一个 VueJS 应用程序在 KeystoneJS 以外的服务器上运行。 我想将来自 VueJS 应用程序的请求发送到 Keystone。

如何在版本 4 中激活 CORS?

在索引文件中,首先设置 CORS 配置,如源、标头和方法:

// example for allow all
keystone.set('cors allow origin', true);
keystone.get('cors allow methods', true)
keystone.get('cors allow methods', headers)

然后,您需要在路由文件中应用路由的配置。

将 CORS 应用于所有路由:

app.all('/*', keystone.middleware.cors);

将 CORS 应用于特定/about路由:

app.all('/about', keystone.middleware.cors);

只需将以下代码放在routes/index 中.js

app.use('*', function (req, res, next) {
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-XSRF-TOKEN');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Method', 'GET,POST,PUT,DELETE');
res.header('Access-Control-Allow-Credentials', true);
next();
});
app.options('*', function (req, res) {
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-XSRF-TOKEN');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Method', 'GET,POST,PUT,DELETE');
res.header('Access-Control-Allow-Credentials', true);
res.sendStatus(200);
});

最新更新