【发布时间】:2021-04-08 19:17:12
【问题描述】:
我在我的 react 应用程序中遇到了很多关于 CORS 的问题,经过大量研究后发现我必须使用代理。
我尝试通过添加在 package.json 中使用代理
"proxy": "https://api.clashroyale.com/",
然后我尝试删除上面的内容并使用以下内容创建 setupProxy.js:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/v1/players',
createProxyMiddleware({
target: 'https://api.clashroyale.com/',
changeOrigin: true,
})
);
};
我的请求在 app.js 中看起来像这样,当单击按钮时会发生这种情况:
const clicksearch = () => {
const headers = {
"Authorization": "Bearer token",
"Content-Type": "application/json",
}
axios.get("v1/players/#123TAG", {headers})
.then(response => {
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
}
我也尝试在 .get 中使用https://api.clashroyale.com/v1/players/#123TAG,但也没有运气。任何关于如何解决这个问题的提示都会很棒
使用https://api.clashroyale.com/v1/players/#123TAG作为获取请求时从服务器得到的响应
Access to XMLHttpRequest at
'https://api.clashroyale.com/v1/players/%232Y900L99' from origin
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
而我在使用 v1/players/#123TAG 时得到的响应是
GET http://localhost:3000/v1/players/%232Y900L99 403 (Forbidden)
【问题讨论】: