Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

为什么传进去一个object,axios会在ajax请求中转化成form data?

config.js

/**
 * Created by root on 2017/4/22.
 **/
import Qs from 'qs'
export default {
  // 请求方法同上
  method: 'post',

  // 基础url前缀
  baseURL: 'http://10.10.252.252:8080/api/dm/',

  // 拦截处理请求数据
  transformRequest: [function (data) {
    data = Qs.stringify(data);
    return data;
  }],

  // 拦截处理响应数据
  transformResponse: [function (data) {
    return data;
  }],

  // 请求头信息
  headers: {

  },

  //post参数,使用axios.post(url,{},config);如果没有额外的也必须要用一个空对象,否则会报错
  data:{

  },

  //设置超时时间
  timeout: 1000,

  // 携带凭证
  withCredentials: true,

  //返回数据类型
  responseType: 'json'
}

api.js

/**
 * Created by root on 2017/4/22. api.js
 **/
import router from 'src/router'
import axios from 'axios'
import config from './config'
import { Message } from 'element-ui';

class API {
  post(params) {
    config.data = params.data
    return axios.post(params.url,config.data,config)
  }
  showMsg(type,msg){
    Message({
      type:type,
      message:msg
    })
  }
}

const api = new API()

// 请求拦截
axios.interceptors.request.use(function (config) {
  return config;
}, function (error) {
  console.log(error)
  return Promise.reject(error);
});

// 响应拦截
axios.interceptors.response.use(function (response) {
  let data = response.data
  // 请求不成功
  if(data.status !== 0){
    api.showMsg('info',data.msg)
  }
  // 会话超时,返回登陆页
  if(data.need_login === 1){
    router.replace('login')
  }
  return response;
}, function (error) {
  console.log(error)
  return Promise.reject(error)
});

export default API;

login请求

data() {
  return {
    logoSrc:logoSrc,
    loginData:{
      opr:'login',
      data:{
        user_name:'',
        psw:''
      }
    }
  }
},
login:function(){
    let self = this
    let params = {
      url:'login.do',
      data:this.loginData
    }
    api.post(params).then(function (response) {
      var data = response.data
      if(data.status === 0){
        api.showMsg('success',data.msg)
      }
    }).catch(function () {

    });
  }

图片描述


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你的Qs.stringify(data)将数据转换了

参考:https://www.npmjs.com/package/qs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...