【问题标题】:TypeError: NetworkError when attempting to fetch resource类型错误:尝试获取资源时出现网络错误
【发布时间】:2019-09-04 12:40:03
【问题描述】:

我遇到了这个问题:

Response { type: "cors", url: "http://localhost:3000/api/marks",
redirected: false, 
status: 200, 
ok: true, 
statusText: "OK", 
headers: Headers, 
body: ReadableStream, 
bodyUsed: true }
MarkService.js:5
Cross-Origin Request Blocked: 
The Same Origin Policy disallows reading the remote resource at      
http://localhost:3000/api/marks. (Reason: CORS request did not succeed). 

这是它指向的地方

class MarkService {
  constructor() {
    this.URI = `localhost:3000/api/marks`;
  }

  async getMarks() {
    const response = await fetch(this.URI);
    const marks = await response.json();
    return marks;
  }
}
export default MarkService;

我正在尝试在后端使用 express 并在前端使用 Webpack 制作应用程序。 我在后端有一个 Rest API,我不能在前端使用它。

我将 Ubuntu 与 Mozilla Firefox 66.0.2 和 Nodejs 11.13.0 一起使用

当我使用控制台时,它说问题出在它里面

【问题讨论】:

  • 粘贴完成错误
  • 开发工具的“网络”选项卡上会发生什么?
  • 尝试一次谷歌的网站而不是本地主机。
  • 我没有尝试连接到 localhost:3000/api/marks(我有 Rest API)
  • 我已将网址更改为 www.google.com,我发现它试图获取 localhost:8080/www.google.com

标签: javascript node.js webpack


【解决方案1】:

我可以看到这个错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/marks. (Reason: CORS request did not succeed)

它表示发生了 CORS 错误,这是因为前端和后端托管在不同的域或端口下(如果在 localhost 上),让我们进一步解释一下。

代表跨域资源共享的 CORS 是一种仅适用于 Javascript(浏览器)的安全策略,它阻止网站使用 AJAX 访问其他网站,除非它们使用标头明确批准。

要解决这个问题,您需要在服务器端的响应中传递某些标头,以批准请求域、标头和方法的 CORS

您可以阅读此article 以深入了解 CORS 或者您可以查看此link 以了解如何解决您面临的问题

还有这个 NPM Package 供 nodejs 帮助你处理 CORS

【讨论】:

    猜你喜欢
    • 2017-07-31
    • 2020-04-20
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2021-05-23
    • 2020-03-29
    相关资源
    最近更新 更多