【发布时间】:2020-05-21 04:01:49
【问题描述】:
我已经找到了 this 这已经帮助了我,但是在我的 proxy.js 中添加了这样的标题之后:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(function(req, res, next) {
//adding headers to allow CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(proxy('/api', { target: 'http://localhost:8080' }));
}
在 fetch() 中,我还添加了标题以确保它正常工作:
fetch('http://localhost:8080/api',{
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(console.log)
}
我仍然收到错误:TypeError:“尝试获取资源时出现网络错误。”
this.setState({ contacts: data }) 应该存储由我的后端 Java 程序提供的 JSON 对象。 JSON 对象位于 localhost:8080/api 并且只是字符串
我的 React 前端在 localhost:3000 上运行
The Response Header looks like this
为了不出现 CORS 错误,我在哪里需要此标头,最好我希望在没有 npm 库“cors”或任何浏览器插件的情况下工作。我也应该用 localhost:8080 替换 '*' 如果我没记错的话,对吧? 我的最终目标是将这些字符串动态地放入 PrimeReact 组件(A 表)中。
编辑:sideshowbarker 请求的完整错误消息:
警告:
跨域请求被阻止:同源规则禁止读取http://localhost:8080/api处的外部资源。 (原因:CORS 预检通道不成功)。
警告:
跨域请求被阻止:同源规则禁止读取http://localhost:8080/api处的外部资源。 (原因:CORS 预检通道失败)。
错误:
TypeError:“尝试获取资源时出现网络错误。
//是德文所以无法上传截图,翻译一下 我忘了提到我也把@CrossOrigin 放在我的 Restcontroller 上
【问题讨论】:
-
浏览器在 devtools 控制台中记录的完整错误消息是什么?
标签: reactjs spring proxy cors response