axios配置post请求

842 阅读1分钟
// 配置axios post请求为application/x-www-form-urlencoded,默认为application/json
server.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
server.defaults.transformRequest = [
  function transform(data) {
    if (data) {
      let str = ''
      const keys = Object.keys(data)
      keys.forEach((key, index) => {
        const value = data[key]
        if (index === keys.length - 1) {
          str += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        } else {
          str += `${encodeURIComponent(key)}=${encodeURIComponent(value)}&`
        }
      })
      return str
    }
    return data
  }
]