【问题标题】:No 'Access-Control-Allow-Origin' header when fetch data with REACT from API使用 REACT 从 API 获取数据时没有“Access-Control-Allow-Origin”标头
【发布时间】:2021-11-08 10:22:22
【问题描述】:

我有一个从公司 API 获取产品的测试。

他们告诉我:

CORS 允许的本地开发来源是“http://localhost:1229”

所以我在 package.json 中设置了这样的代理:

"proxy": "http://localhost:1229",

我的要求是:

const apiLink = 'https://example.com/api/checkout/products/';

    fetch(apiLink, {
        method: 'POST'
    }).then(returnedData => {
        console.log(returnedData)
    }).catch(error => {
        console.log(error)
    });

但我仍然收到此错误

Access to fetch at 'https://...' from origin 'http://localhost:3000' has been blocked by CORS policy: 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

【问题讨论】:

  • 在这种情况下,您需要将您的 http://localhost:3000 作为允许的主机放入您的后端 api。

标签: javascript reactjs api


【解决方案1】:

CORS 允许从源 http://localhost:1229 获取内容 所以,尝试在 http://localhost:1229 上运行开发服务器

使用命令 在 Linux 上
PORT=1229 react-scripts start
在窗户上
set PORT=1229 && react-scripts start

或更改 package.json
"start": "PORT=1229 react-scripts start"
"start": "set PORT=1229 && react-scripts start"

【讨论】:

  • 兄弟我该怎么做?我在哪里可以设置这个“开始”:“set PORT=1229 && react-scripts start”???
  • 找到文件 package.json 会有“脚本”对象,并且会有一些键,比如(启动、构建、测试),如果你在 linux 上,只需将启动值更改为 PORT=1229 react-scripts startset PORT=1229 && react-scripts start如果你在 Windows 上
  • 谢谢你uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu 兄弟我爱你
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 2016-05-13
  • 2017-09-19
  • 2015-04-02
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多