当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 完美解决axios跨域请求出错的问题

完美解决axios跨域请求出错的问题

2018年02月07日  | 移动技术网IT编程  | 我要评论

javzoo上不去,马桶台是哪个台,万部电影

错误信息:

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为例:

添加一个拦截器类:

public class processinterceptor implements handlerinterceptor {

  @override
  public boolean prehandle(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o) throws exception {
    httpservletresponse.setheader("access-control-allow-origin", "*");
    httpservletresponse.setheader("access-control-allow-headers", "content-type,content-length, authorization, accept,x-requested-with");
    httpservletresponse.setheader("access-control-allow-methods","put,post,get,delete,options");
    httpservletresponse.setheader("x-powered-by","jetty");

    string method= httpservletrequest.getmethod();
    if (method.equals("options")){
      httpservletresponse.setstatus(200);
      return false;
    }
    system.out.println(method);
    return true;
  }
  @override
  public void posthandle(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o, modelandview modelandview) throws exception {
  }
  @override
  public void aftercompletion(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, object o, exception e) throws exception {
  }
}

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

<mvc:interceptors> 
    <bean class="cn.tfzc.ssm.common.innterceptor.processinterceptor"></bean> 
  </mvc:interceptors> 

至此,问题已经解决:

以上这篇完美解决axios跨域请求出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网