如何在 KeystoneJSv4 中设置 CORS
How to set CORS in KeystoneJSv4
我在 KeystoneJS 以外的服务器上有一个 VueJS 应用程序 运行。
我想从 VueJS 应用程序向 Keystone 发送请求。
如何在版本 4 中激活 CORS?
在您的索引文件中,首先设置您的 CORS 配置,例如来源、header 和方法:
// 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);
});
我在 KeystoneJS 以外的服务器上有一个 VueJS 应用程序 运行。 我想从 VueJS 应用程序向 Keystone 发送请求。
如何在版本 4 中激活 CORS?
在您的索引文件中,首先设置您的 CORS 配置,例如来源、header 和方法:
// 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);
});