spring boot和React跨域请求解决
2019-04-10 Yazzyk首先是在React,前端上只需要注意请求是POST请求,因为GET请求会有一个错误,然后就是用fetch传输了
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
let data = new FormData();
data.append("userName",values.userName);
data.append("password",values.password);
data.append("remember",values.remember);
fetch("http://localhost:8080/post",{
method: 'POST',
body : data
}).catch();
}
});
};
然后主要是在spring boot这里,后端控制器要写入一行
@CrossOrigin(origins = "http://localhost:3000")
然后就可以了
(2019.05.22)
我发现似乎还是有问题,后来又有了新的方法
新建一个CrosFilter
类,实现Filter
接口
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author blankyk
*/
@Component
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
- 本文链接: spring boot和React跨域请求解决
- 版权声明: 本作品由Yazzyk采用知识共享署名-非商业性使用 4.0
国际许可协议进行许可。
基于Yazzyk's Blog上的作品创作。转载请注明出处!