【问题标题】:Error: Not allowed by CORS issue inside of Express app错误:Express 应用程序内部的 CORS 问题不允许
【发布时间】:2020-08-20 02:55:33
【问题描述】:

我向我们的任何 CRUD 路由发出请求,我收到此错误。我对服务器端代码的熟悉程度不足以为问题提供更好的细节。顺便说一句,我在 Docker 中运行这一切。

const clientHost = `http://${process.env.CLIENT_HOST}`;

const whitelist = [clientHost];

const corsOptions = {
  origin(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      console.log(origin);
      callback(new Error("Not allowed by CORS"));
    }
  }
};

app.use(cors(corsOptions));

收到错误:

Error: Not allowed by CORS
at origin (/backend/server.js:24:16)
 at /backend/node_modules/cors/lib/index.js:219:13
 at optionsCallback (/backend/node_modules/cors/lib/index.js:199:9)
  at corsMiddleware (/backend/node_modules/cors/lib/index.js:204:7)
 at Layer.handle [as handle_request] (/backend/node_modules/express/lib/router/layer.js:95:5)
 at trim_prefix (/backend/node_modules/express/lib/router/index.js:317:13)
 at /backend/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/backend/node_modules/express/lib/router/index.js:335:12)
at next (/backend/node_modules/express/lib/router/index.js:275:10)
 at expressInit (/backend/node_modules/express/lib/middleware/init.js:40:5)

【问题讨论】:

    标签: node.js express server cors


    【解决方案1】:

    export CLIENT_HOST= 无论您的console.log(origin) 在您的错误之前打印到终端什么:CORS 错误不允许(没有http://)

    完全停止您的节点进程,然后在您导出 CLIENT_HOST 变量的同一终端窗口中重新启动它。

    【讨论】:

      【解决方案2】:

      您试图只允许特定 IP 访问您的系统,白名单 IP 来自 process.env.CLIENT_HOST,您需要从源添加 IP 地址并将其添加到 process.env.CLIENT_HOST。

      【讨论】:

        猜你喜欢
        • 2013-03-29
        • 2022-01-14
        • 2017-12-28
        • 2012-06-15
        • 2019-05-19
        • 2017-12-28
        • 2021-05-03
        • 1970-01-01
        相关资源
        最近更新 更多