Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

封装axios请求时,设置了‘axios.defaults.withCredentials = true’,但是发请求时请求头内没有带上cookie信息 #962

Closed
JiangDing1990 opened this issue Aug 14, 2018 · 4 comments

Comments

Projects
None yet
3 participants
@JiangDing1990
Copy link

commented Aug 14, 2018

封装axios请求时,设置了axios.defaults.withCredentials = true,但是发请求时请求头内没有带上cookie信息。request.js代码如下:

import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

// 超时
axios.defaults.timeout = 15000
axios.defaults.withCredentials = true

axios.interceptors.request.use(config => {
  return config
}, error => {
  console.log(error) // for debug
  Promise.reject(error)
})

axios.interceptors.response.use(
  response => response,
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

// 封装的
const ajax = {
  get(url, data) {
    return new Promise((resolve, reject) => {
      axios.get(url, qs.stringify(data)).then((response) => {
        resolve(response.data)
      }, (response) => {
        reject(response.data)
      })
    })
  },
  
  post(url, data) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(data)).then((response) => {
        resolve(response.data)
      }).catch((response) => {
        reject(response.data)
      })
    })
  }
}

Vue.prototype.$ajax = ajax

export default axios

以上,找了很久原因,一直没找到。求助

@PanJiaChen

This comment has been minimized.

Copy link
Owner

commented Aug 14, 2018

@JiangDing1990

This comment has been minimized.

Copy link
Author

commented Aug 14, 2018

@PanJiaChen 谢谢提醒。我后来仔细检查发现是mock.js更改XMLHttpRequest为另外一个对象,导致无法携带cookie,我移除掉mock文件夹的引用时,发现代码报错了。。目前问题还没有得到解决,貌似是main.js文件下permission.js的引用导致的错误,明天再看看原因在哪里

@PanJiaChen

This comment has been minimized.

Copy link
Owner

commented Aug 15, 2018

@PanJiaChen PanJiaChen closed this Aug 15, 2018

@Aysnine

This comment has been minimized.

Copy link
Contributor

commented Oct 13, 2018

暂时性修复,在引入 Mock 之后使用如下代码

  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false
    }
    this.proxy_send(...arguments)
  }

Repository owner deleted a comment from caojiwang Oct 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.