【问题标题】:How to resolve cors origin exception如何解决 cors 起源异常
【发布时间】:2021-09-11 16:01:14
【问题描述】:

我们将 nodejs 应用程序部署到 aws,但在访问任何 api 时都会出现此错误,

Access to XMLHttpRequest at 'https://vkluy41ib9.execute-api.ap-south-1.amazonaws.com/dev/api/auth/login' from origin 'https://cmc-app.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在的问题是,如果我们的节点应用程序托管在 localhost 上,它工作正常,但部署在实时服务器上却抛出错误

这是我们的代码:

app.options(cors());
app.use(function (req, res, next) {
  //Enabling CORS
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization"
  );
  next();
})

【问题讨论】:

  • 你能看到检查器中的标题吗?
  • 这可能是在 aws 控制台级别找到的设置。

标签: node.js express cors


【解决方案1】:

如果你想使用cors()那么你需要写:

app.options("*", cors());

否则将无法正确注册。使用此方法,从cors() 返回的处理程序将用于所有OPTIONS-requests。

第二部分app.use 是不必要的,因为它与之前的方法几乎相同。

要在第二部分中得到你想要的结果,你可以这样写:

app.options("*", cors({
  methods: ["GET", "HEAD", "OPTIONS", "POST", "PUT"],
  allowedHeaders: ["origin", "X-Requested-With", "Content-Type", "Accept", "x-client-key", "x-client-token", "x-client-secret", "Authorization"]
}));

此处列出了 cors 的所有配置选项:https://www.npmjs.com/package/cors#configuration-options

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多