【发布时间】:2021-05-17 05:09:25
【问题描述】:
我对 npm(和“兄弟姐妹”)都是新手,并且会做出反应。我仍然设法创建了一个用户界面。我的问题是从运行在 tomcat 上的服务器获取数据。
我收到以下错误消息:
跨域请求被阻止:同源策略不允许读取位于http://127.0.0.1:8080/CabinCTRLWS/webresources/service/clients 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
请注意,我尝试访问本地主机 http://127.0.0.1:8080/CabinCTRLWS/webresources/service/clients。 我还尝试了 localhost 和主机的实际 IP 地址。
仅供参考 - 一切都在虚拟 (KVM) 机器上运行 - 没关系。
将地址粘贴到 firefox、chrome 或 Postman 中会产生预期的结果。
[{"key":"cff3da01-a4ed-4304-9138-5c97398c9005","userAgent":"Mozilla/5.0 (X11; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0","mod":""}]
我稍后会尝试上传服务器部分的战争和反应代码的 zip。
我尝试了 3 个不同“教程”的解决方案。
- https://www.youtube.com/watch?v=w7ejDZ8SWv8
- https://reactjs.org/docs/faq-ajax.html
- https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/
仍然无法正常工作。
我需要帮助的是,从内部反应代码,调用我的服务,最后得到一个我可以循环的结果。
代码:
componentDidMount(){
alert("componentDidMount");
fetch("http://127.0.0.1:8080/CabinCTRLWS/webresources/service/clients")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
clients: result.clients
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
正如我所说,在 npm 和 react 方面,我完全是个菜鸟。我的 JS 有点老派。 我认为有很多改进,我欢迎任何 cmets,但我最想解决 CORS 问题。
【问题讨论】:
-
检查你的服务器配置,它应该允许跨域请求
-
@lissettdm。我没有检查服务器配置,因为它可以在 firefox、chrome 和 Postman 中使用。但我会确保为 tomcat 添加 cors 过滤器。感谢您的评论。
-
解决方案是配置你的服务器。使用 firefox、chrome 和 Postman 测试 api 不会出现此错误。
-
@lissettdm - 谢谢。第一次尝试时,我未能在 tomcat 中获得正确的 conf。现在它起作用了。谢谢。
标签: javascript reactjs ajax cors localhost