【问题标题】:How to set CORS in KeystoneJSv4如何在 Keystone JS v4 中设置 CORS
【发布时间】:2020-12-02 19:31:58
【问题描述】:

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

如何在版本 4 中激活 CORS?

【问题讨论】:

    标签: keystonejs


    【解决方案1】:

    在您的索引文件中,首先设置您的 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);
    

    【讨论】:

    • 非常感谢您的反馈。我没有将 CORS 应用于路由!效果很好。
    • 刚看完最后一个应该也是keystone.get('cors allow methods', true)
    【解决方案2】:

    只需将以下代码放入 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);
        });
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2018-08-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多