类型错误:尝试获取资源时出现网络错误 [英] TypeError: NetworkError when attempting to fetch resource
问题描述
我遇到了这个问题:
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,我不能在前端使用它.
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.
我使用 Ubuntu 和 Mozilla Firefox 66.0.2 和 Nodejs 11.13.0
I'm using Ubuntu with Mozilla Firefox 66.0.2 and Nodejs 11.13.0
当我使用控制台时,它说问题出在它身上
When I use the console, it said that the problem is in it
推荐答案
我可以看到这个错误
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 错误,这是因为如果在本地主机上,前端和后端托管在不同的域或端口下,让我们进一步解释一下.
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 代表跨源资源共享,是一种仅适用于 Javascript(浏览器)的安全策略,它会阻止网站使用 AJAX 访问其他网站,除非它们使用标头明确批准.
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、标头 &方法
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 article for deep knowledge about CORS Or you can check this link to know how to solve the issue your facing
还有这个 NPM Package 用于 nodejs 来帮助你处理 CORS
And there is this NPM Package for nodejs to help you with CORS
这篇关于类型错误:尝试获取资源时出现网络错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!