node.js - 如何修复 "Response to preflight request doesn' t 通过访问控制检查 : It does not have HTTP ok status"error in react app with nodejs api

标签 node.js reactjs cors

我一直在尝试从本地开发服务器(web-pack 开发服务器)上的浏览器中运行的React应用程序进行API调用(在本地主机上运行express的nodejs)。一切都运行良好,直到我尝试调用 api。它们都在不同的端口上运行。

我尝试将 cors header (MDN 推荐)添加到 post 调用(来自浏览器中的应用程序)和 Nodejs API 的响应,但这些都没有解决问题。

API 调用代码(在浏览器中):

const headers = {
  'Content-Type': 'application/json',
  'access-token': '',
  'Access-Control-Allow-Origin': '*',
}

export default async () => {
  try {
    const body = JSON.stringify({
      test: true,
    })
    const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
      method: 'POST',
      headers,
      body,
    })
    console.log(response)
  } catch (e) {
    return e
  }
}

API中间件(在nodejs中):

// Verify All Requests
app.use(VerifyToken)

// Compress
app.use(compression())

// Helmet middlware
app.use(helmet())

// Body Parser
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(bodyParser.json())

预期结果是仅给出 200 状态代码并响应数据。

实际输出是:

OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

最佳答案

由于您使用的是webpack-dev-server,您可以使用proxy选项 DevServerProxy .

您的配置将如下所示:

// webpack.config.js
devServer: {
    proxy: {
      '/internal': 'http://localhost:1337'
    }
  }

由于我在您的问题上看不到您的 express 路由,因此我推测如果您的 API 位于 /internal 上,则使用代理路由> 端点那么你应该像这样修改你的 React 代码:

const response = await fetch('/internal/provider/check_email_exist', {
   method: 'POST',
   headers,
   body,
})

如您所见,我省略了 https://localhost:1337 因为 webpack-dev-server 中的 proxy 选项将处理它将重定向到http://localhost:1337。希望对你有帮助。干杯,西格弗里德。

编辑

正如对您问题的评论所指出的,您应该在 express 服务器上设置 header ,而不是在客户端上,对于此任务,您可以使用 cors-middleware包。

关于node.js - 如何修复 "Response to preflight request doesn' t 通过访问控制检查 : It does not have HTTP ok status"error in react app with nodejs api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083049/

相关文章:

javascript - 以编程方式启动 crossbar.io

javascript - 如何在 next.js 页面中实现 Razorpay 支付按钮

node.js - 使用 fs 流获取图片的 api 使用 connect-history-api-fallback 返回 304

javascript - 我应该在构造函数上方或下方包含 module.exports

javascript - 当我想使用外部 "_this is undefined"关键字时出现 "this"错误

javascript - 在 Polymer 中使用 core-ajax 的 CORS 错误

javascript - 由于 CORS 错误 : “The value of the ' Access-Control-Allow-Origin' header must not be the wildcard '*' ”,Socket.io 和 Express 应用程序无法连接

php - 带有 php session 的 CORS

javascript - 如何调整 while 循环中的变量范围以匹配 CoffeeScript 中的所有正则表达式?

javascript - 如何设置状态以在 react 中键入记录