【问题标题】:Unable to fetch JSON from Express server using Fetch api无法使用 Fetch api 从 Express 服务器获取 JSON
【发布时间】:2020-05-31 05:22:10
【问题描述】:

在端口 8080 上运行的 Express 服务器中,我有;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

来自 8081 端口的请求

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))

我得到的错误:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

如果我只是在浏览器上手动输入 express url,我会看到我正在尝试获取的 JSON。

我已经阅读了多篇文章来解决这个问题,但我似乎仍然无法解决它。

我应该如何获取以避免此错误?

【问题讨论】:

    标签: javascript express cors es6-promise fetch-api


    【解决方案1】:

    您从不同的端口 (8081) 获取数据,这就是您收到 CORS 错误消息的原因。更改访问控制策略如下:

      res.header("Access-Control-Allow-Origin", "http://localhost:*");
    

    这个link可以派上用场。

    【讨论】:

      【解决方案2】:

      你可以使用cors来摆脱这个;

      const express = require('express')
      const cors = require('cors')
      const app = express()
      
      app.use(cors())
      

      【讨论】:

      • @Vid 我确实尝试安装和使用 cors 但没有成功
      • 我怀疑你可能在 API 路由之后初始化 cors。请检查。
      • @Vid,是的,在初始化 cors 时不再出现相同的错误,但我的 JSON 未定义
      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 2021-09-08
      • 2016-08-03
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多