我正在尝试为后端开发一个带Spring Boot的应用程序,为前端开发Angular 2。
实际上,当我从spring访问mvc登录页面时,我遇到了连接问题。
我遇到以下问题:
(控制台)
我为FrontEnd端口设置了全局Cors配置。我的请求返回响应状态200.但我无法访问响应,因为我在控制台中收到错误消息。
Spring dosnt有错误。
答案 0 :(得分:8)
首先需要了解Cors配置是否在后端添加。您不需要为Angular2 App的每个请求发送cors标头。了解这一点,可以通过在Spring安全配置类中添加全局CORS配置来轻松解决此问题。
首先,您需要创建一个过滤器bean:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsFilter implements Filter{
public MyCorsFilter () {
super();
}
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
// without this header jquery.ajax calls returns 401 even after successful login and SSESSIONID being succesfully stored.
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Origin, Content-Type, Version");
response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");
final HttpServletRequest request = (HttpServletRequest) req;
if (!request.getMethod().equals("OPTIONS")) {
chain.doFilter(req, res);
} else {
// do not continue with filter chain for options requests
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
第2步:在spring security配置类中添加:
@Autowired
private MyCorsFilter myCorsFilter;
//CORS
http.addFilterBefore(myCorsFilter, ChannelProcessingFilter.class);
编辑: 此配置假定您在localhost:3000
运行angular2应用程序答案 1 :(得分:1)
如果你正在使用Spring 4.2和更多版本,那么开箱即用的CORS有第一类支持。阅读此page。
您可以通过在班级定义以下注释来逃避:
@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)