vue-resource get/post请求如何携带cookie的问题以及springmvc拦截问题

当我们使用vue请求的时候,我们会发现请求头中没有携带cookie传给后台,我们可以在请求时添加如下代码:
vue.http.options.xhr = { withCredentials: true}; 的作用就是允许跨域请求携带cookie做身份认证的;
vue.http.options.emulateJSON = true; 的作用是如果web服务器无法处理 application/json的请求,我们可以启用 emulateJSON 选项;
启用该选项后请求会以 application/x-www-form-urlencoded 作为MIME type, 和普通的html表单一样。 加上如下代码,get请求返回的代码会
携带cookie,但是post不会;

为了方便,我们这边是封装了一个get请求,只要在get请求添加参数 { credentials: true } 即可使用;

复制代码
const ajaxGet = (url, fn) => {
  let results = null;
  Vue.http.get(url, { credentials: true }).then((response) => {
    if (response.ok) {
      results = response.body;
      fn(1, results);
    } else {
      fn(0, results);
    }
  }, (error) => {
    if (error) {
      fn(0, results);
    }
  });
};
复制代码

如上只会对get请求携带cookie,但是post请求还是没有效果的,因此在post请求中,我们需要添加如下代码:

Vue.http.interceptors.push((request, next) => {
  request.credentials = true;
  next();
});

Vue.http.interceptors 是拦截器,作用是可以在请求前和发送请求后做一些处理,加上上面的代码post请求就可以解决携带cookie的问题了;
因此我们的post请求也封装了一下,在代码中会添加如上解决post请求携带cookie的问题了;如下代码:

复制代码
const ajaxPost = (url, params, options, fn) => {
  let results = null;

  if (typeof options === 'function' && arguments.length <= 3) {
    fn = options;
    options = {};
  }
  Vue.http.interceptors.push((request, next) => {
    request.credentials = true;
    next();
  });
  Vue.http.post(url, params, options).then((response) => {
    if (response.ok) {
      results = response.body;
      fn(1, results);
    } else {
      fn(0, results);
    }
  }, (error) => {
    if (error) {
      fn(0, results);
    }
  })
};

拦截器的配置 

<!-- 登录拦截器 -->  
<mvc:interceptors>   
  <mvc:interceptor>   
    <mvc:mapping path="/admin/*"/> <!-- 拦截路径 -->  
    <mvc:exclude-mapping path="/admin/toLogin.action"/>  <!-- 排除的拦截路径 -->  
    <bean class="com.edwin.admin.interceptor.LoginInterceptor"></bean>   
  </mvc:interceptor>   
</mvc:interceptors>  


public class LoginedInterceptor implements HandlerInterceptor  {  
    
  private final String ADMINSESSION = "loginedsession";  
  //拦截前处理  
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {  
    Object sessionObj = request.getSession().getAttribute(ADMINSESSION);  
    if(sessionObj!=null) {   
      return true;  
    }   
    response.sendRedirect("toLogin.action");  
    return false;  
  }  
  //拦截后处理  
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception { }  
  //全部完成后处理  
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception { }  
}  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值