解决axios跨域请求出错的问题状态码403错误

错误信息:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403

随着前端框架的发展,如今前后端数据分离已经成了趋势,也就是说,前端只需要用ajax请求后端的数据合成页面,后端仅仅提供数据接口,给数据就行,好处就是前端程序员再也不用在自己的本地搭建Web服务器,前端也不需要懂后端语法,后端也不需要懂前端语法,那么简化了开发配置,也降低了合作难度。

常规的GET,POST,PUT,DELETE请求是简单请求(相对于OPTIONS请求),但是OPTIONS有点儿特别,它要先发送请求问问服务器,你要不要我请求呀,要我就要发送数据过来咯(这完全是根据自己的理解写的,如果有误,敬请谅解,请参考阮一峰大神原文。)

在Vue的项目里,Http服务采用Axios,而它正是采用OPTIONS请求。

如果仅仅在header里面加入: 'Access-Control-Allow-Origin':*,是并不能解决问题的,错误就是如文章开头所示。

这儿就需要后台对OPTIONS请求额外处理。

本文以Spring MVC为例:

添加一个拦截器类:

[java]  view plain  copy
  1. public class ProcessInterceptor implements HandlerInterceptor {  
  2.   
  3.   
  4.     @Override  
  5.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {  
  6.   
  7.         httpServletResponse.setHeader("Access-Control-Allow-Origin""*");  
  8.   
  9.         httpServletResponse.setHeader("Access-Control-Allow-Headers""Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
  10.   
  11.         httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
  12.   
  13.         httpServletResponse.setHeader("X-Powered-By","Jetty");  
  14.   
  15.   
  16.         String method= httpServletRequest.getMethod();  
  17.   
  18.         if (method.equals("OPTIONS")){  
  19.             httpServletResponse.setStatus(200);  
  20.             return false;  
  21.         }  
  22.   
  23.         System.out.println(method);  
  24.   
  25.         return true;  
  26.     }  
  27.   
  28.     @Override  
  29.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {  
  30.   
  31.     }  
  32.   
  33.     @Override  
  34.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {  
  35.   
  36.     }  
  37. }  


在spring-mvx.xml配置Spring 拦截器:

[html]  view plain  copy
  1. <mvc:interceptors>  
  2.        <bean class="cn.tfzc.ssm.common.innterceptor.ProcessInterceptor"></bean>  
  3.    </mvc:interceptors>  

猜你喜欢

转载自blog.csdn.net/m0_37836194/article/details/79173463
今日推荐