vue-element-manage icon indicating copy to clipboard operation
vue-element-manage copied to clipboard

qs无法使用

Open wusaneryi opened this issue 5 years ago • 1 comments

引用qs后,使用qs.stringify(data); 错误:stringify is not a function

wusaneryi avatar May 07 '20 09:05 wusaneryi

引用qs后,使用qs.stringify(data); 错误:stringify is not a function

如果需要post表单格式的数据可以使用URLSearchParams或FormData:

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/user', params);

封装:

function objToParams(data) {
  var params = new URLSearchParams();
  Object.keys(data).forEach(key => params.append(encodeURIComponent(key), encodeURIComponent(obj[key])))
  return params;
}

还可以自己进行序列化:

function dataSerializer(data = {}) {
  const keys = Object.keys(data);
  const params = keys.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
  return params.join('&');
}

使用:

axios({
  url: '/api/lockServer/search',
  method: 'post',
  data: dataSerializer ({
    username: 'admin',
    pwd: 'admin'
  }),
})

或者

axios({
  url: '/api/lockServer/search',
  method: 'post',
  data: {
    username: 'admin',
    pwd: 'admin'
  },
  transformRequest: [(data) => dataSerializer (data)]
})

Wluyao avatar May 10 '20 08:05 Wluyao