Reactjs 从前端发布数据时获取CORS问题(React)
我正在使用axios从react向spring boot后端发布数据。请参阅下面的react代码Reactjs 从前端发布数据时获取CORS问题(React),reactjs,spring-boot,cors,Reactjs,Spring Boot,Cors,我正在使用axios从react向spring boot后端发布数据。请参阅下面的react代码 const handleSubmit = (e) =>{ e.preventDefault() alert( "Username "+ username + " Password "+password); axios.post('http://localhost:8080/sign-up',{ username:u
const handleSubmit = (e) =>{
e.preventDefault()
alert( "Username "+ username + " Password "+password);
axios.post('http://localhost:8080/sign-up',{
username:username,
password:password})
};
下面是我的spring代码。
@邮递(“/注册”)
公共字符串注册(@RequestBody User){
我在spring boot的控制器中插入了以下行
@CrossOrigin(origins = "http://localhost:3000")
但是上面的解决方案不起作用。我怀疑在post看涨期权期间,正在进行看涨期权,以检查资源,在这种情况下,只有cors问题发生。感谢对此问题的任何意见。我最近遇到了类似的问题
我又迈出了一步,暂时从POM中删除了spring boot starter安全性,因为它阻止了未经授权的呼叫。因此我发现这是我的问题。我必须为spring security配置CORS,然后我让它工作了。对于含糊不清的回答,我深表歉意,但我希望它能帮助您从另一个方向看问题这可能会对您有所帮助。我找到了上述问题的解决方案。当不同域之间发生通信时,就会出现此cors问题。因此,我在SecurityConfig类的configure()方法中添加了以下行
http.cors();
然后我实现了以下CustomCorsFilter类。
@组成部分
公共类CustomCorsFilter扩展了OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Allow, authorization, content-type, xsrf-token");
httpServletResponse.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(httpServletRequest.getMethod())) {
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
}
现在没有cors问题。我能够克服这个cors问题。我已经为将来的任何需要发布了答案。可能会有帮助=>
http.cors();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Allow, authorization, content-type, xsrf-token");
httpServletResponse.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(httpServletRequest.getMethod())) {
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
}