如何修复使用 FastAPI、React 和 Axios 引发"blocked by CORS policy"错误?



我试图使用axios获取数据,但遇到以下错误:

No 'Access-Control-Allow-Origin'

我试图找到一个解决方案,但没有找到合适的解决方案,包括FastAPI、React和Axios。

这是我的后端:

origins = ['https://localhost:3000', 'https://localhost:8080']
app.add_middleware(
CORSMiddleware,
allow_origins = [origins],
allow_credentials = True,
allow_methods = ["*"],
allow_headers = ["*"]
)

@app.get('/')
def root():
return {
"Data" : "Working!"
}

下面是我的前端:

const message = async () => {
try {
let res = await axios.get("http://127.0.0.1:8080/");
let result = res.data;
console.log(result);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
message();
}, []);

错误:

Access to XMLHttpRequest at 'http://127.0.0.1:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在我在本地使用它,在package.json文件中添加代理。但在生产中,它不起作用。然而,我需要一个适当的解决方案,生产级别不使用代理。

请帮我解决这个错误。

您应该使用allow_origins=origins而不使用围绕origins变量的brackers[]

示例

origins = ['http://localhost:3000', 'https://localhost:3000']
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

请查看此答案和此答案以了解更多详细信息。

相关内容

最新更新