代码改变世界

vue-resource get/post请求如何携带cookie的问题

  龙恩0707  阅读(10834)  评论(0编辑  收藏  举报

vue-resource get/post请求如何携带cookie的问题

当我们使用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);
    }
  })
};
复制代码
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示