前端跨域问题
程序员文章站
2024-02-21 23:59:28
...
以前项目中遇到过这个问题,当时解决了,今天又遇到这个问题,一时想不起来了,翻了上个项目的代码,才解决了问题。现在记录下来,防止再忘记了。
这是用后端的方式解决跨域问题,就是在过滤器或者拦截器中加上一段:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
这是完整的拦截器preHandle方法:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
time.set(System.currentTimeMillis());
logger.info("开始进入springmvc,线程id为" + Thread.currentThread().getId() + ",时间为" + time.get());
return true;
}