前后端交互解决跨域请求问题

在前后端分离开发时往往会涉及到前后端分离开发。

可是js禁止了跨域请求。例如api.test.com中的ajax请求如法访问aaa.test.com服务器

这时前后端都得采取一些措施来解决

后端(java):

在拦截器或者过滤器中设置响应头,这里拿springmvc中的拦截器举例:

package cn.creat.zhxy.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AllowOriginInterceptor implements HandlerInterceptor{


@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse res, Object arg2, Exception arg3)
throws Exception {

}


@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}


@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse res,
Object arg2) throws Exception {
res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "0");
        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed","1");
return true;
}


}

前端部分:

(function(){
         $.ajax({
              //加入这几行代码
xhrFields: {
withCredentials: true
},
crossDomain: true,
             
});

这样就解决了跨域问题

你可能感兴趣的:(前后端交互解决跨域请求问题)