我在一个react 前端工作,以图表从一个快速API后端的一些数据.我使用了几个下拉组件来更改所请求数据的月份和年份.对于初始呈现,FETCH请求工作正常,并返回数据和图表显示.一旦我更改了下拉列表,我就会在浏览器控制台中看到以下CORS策略错误.
CORS策略已阻止访问从源https://fake-url.com/endpoint/‘获取http://localhost:3000’:对印前判断请求的响应未通过访问控制判断:请求的资源上不存在"Access-Control-Allow-Origin"标头.如果一个不透明的响应满足您的需求,请将请求的模式设置为‘no-CORS’,以便在禁用CORS的情况下获取资源.
使用FETCH调用react 代码片段:
const [month, setMonth] = useState(1);
const [year, setYear] = useState('2023');
const [revenueData, setRevenueData] = useState({});
useEffect(() => {
const inputs = {
"month": month,
"year": year,
"duration": 1
}
const myHeaders = new Headers();
myHeaders.append("X-API-KEY", "fake-api-key");
myHeaders.append("Content-Type", "application/json");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(inputs),
redirect: 'follow'
};
fetch("https://fake-url.com/endpoint/", requestOptions)
.then(response => response.json())
.then(data => {
setRevenueData((data))
}).catch(error => {
console.log('error', error)
});
}, [month, year]);
我确认我在FastAPI中使用的是CORSMiddleware,设置如下:
app.add_middleware(HTTPSRedirectMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_methods=['*'],
allow_headers=['*']
)
I also confirmed that the backend is returning access-control headers for preflight with an options request in postman as shown:
UPDATE个
网络面板显示第二次请求印前判断成功,但最终因内部服务器错误而失败.这让我想到了: