javascript 类型错误:尝试获取资源时出现网络错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55673803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:34:12  来源:igfitidea点击:

TypeError: NetworkError when attempting to fetch resource

javascriptnode.jswebpack

提问by Rohen

I obtain this problem :

我得到这个问题:

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). 

This is where it points

这是它指向的地方

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;

I'm trying to make a app with express in the backend and Webpack for the frontend. I have a Rest API in the backend and I can't use it on the frontend.

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

I'm using Ubuntu with Mozilla Firefox 66.0.2 and Nodejs 11.13.0

我在 Mozilla Firefox 66.0.2 和 Nodejs 11.13.0 上使用 Ubuntu

When I use the console, it said that the problem is in it

当我使用控制台时,它说问题出在它身上

回答by Anas AL-zghoul

As i can see for this error

正如我所看到的这个错误

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)

it says that a CORS error has occurred, and that's because the front-end and back-end are hosted under different domain or ports if on localhost, lets explain this a little bet further.

它说发生了 CORS 错误,这是因为如果在本地主机上,前端和后端托管在不同的域或端口下,让我们进一步解释一下。

CORS which stands for Cross Origin Resource Sharing is a security policy that applies only to Javascript (Browsers) that blocks websites from accessing other websites using AJAX unless they are explicitly approved using headers.

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

To solve this, you need to pass certain headers in the response from the server side that approves CORS for the requesting domain, headers & methods

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

You can read this articlefor deep knowledge about CORS Or you can check this linkto know how to solve the issue your facing

您可以阅读这篇文章以深入了解 CORS 或者您可以查看此链接以了解如何解决您面临的问题

And there is this NPM Packagefor nodejs to help you with CORS

还有这个用于 nodejs 的NPM 包来帮助你处理 CORS