【发布时间】:2020-09-29 17:56:56
【问题描述】:
我正在尝试使用 fetch() 在我的本地环境中将我的小型 React JS 应用程序与我的 Deno API 后端“连接”。
const apiUrl = `http://localhost:8000`;
try{
fetch(apiUrl)
.then((res) => res.json())
.then((repos) => {
console.log(repos);
setAppState({ loading: false, repos: repos });
});
}catch(err){
console.log(err);
}
我的应用在 localhost:3000 上提供服务,而我的 deno api 在 localost:8000 上提供服务。
但是,我遇到了 CORS 问题:
Access to fetch at 'http://localhost:8000/' 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.
我尝试了一些建议,例如:
将行 '"proxy": "http://localhost:8000" 添加到 reactjs 项目 packages.json'。
或添加:
var options = {
method: 'get',
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*"
},
}
fetch(apiUrl, options)
或添加:
fetch(apiUrl, {mode: 'no-cors'})
但是,在我的情况下没有任何效果。根据建议,总是遇到相同的错误和一些额外的错误。
所以,我需要在我的 reactjs 和 deno api 应用程序中禁用 CORS,以允许前端和后端之间的本地开发人员通信。
【问题讨论】:
-
我上面有同样的问题,下面没有 Deno 解决方案有效?你在 Deno 解决了吗?