我正在尝试使用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.我尝试了一些建议,比如:在reactjs项目packages.json‘中添加行'"proxy": "http://localhost:8000"。
或添加:
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,以允许前端和后端之间的本地开发通信。
发布于 2020-06-10 18:39:20
在我的情况下,解决方案非常简单。
我必须在我的Deno API app.ts中导入oakCors
import { oakCors } from "https://deno.land/x/cors/mod.ts";在此之后,只需在app实例化后添加排除的源:
app.use(
oakCors({
origin: "http://localhost:3000"
}),
);注意:我尝试将原点设置为origin: false,但在我的情况下不起作用。
有关Deno CORS的更多选项,请访问以下链接:https://deno.land/x/cors
发布于 2020-07-02 16:47:46
对我来说,我必须首先将oakCors配置传递给应用程序,然后再传递路由。
app.use(oakCors({
origin: 'http://localhost:4200',
optionsSuccessStatus: 200,
}));
app.use(router.routes());发布于 2020-12-24 05:18:17
这很好用:
app.use(oakCors({ origin: "*" }));https://stackoverflow.com/questions/62301531
复制相似问题