axios奇怪的post请求方式

2018-01-19  本文已影响105人  回不去的那些时光

最近学习了一下vue-cli创建spa(单页面应用),在与后台交互的时推荐使用axios,用了一下,发现了很多坑。这里我主要描述一下axios在发送post请求时的问题

axios在使用post请求时一般是用以下方式

 this.$http.post('user/login', {
        userName: username,
        password: password
      }).then(function(response) {
        console.log('成功信息!');
      }).catch(function(error) {
        console.log('失败信息!');
      });

但是这样请求时一直报405和415的错误,后来发现直接将参数像get请求一样拼接在url后面请求是成功的

this.$http.post('user/login?userName=' + username + '&password=' + 
       password).then(function(response) {
        console.log('成功信息!');
      }).catch(function(error) {
        console.log('失败信息!');
      });

但是这样写会感觉很奇怪,然后就百度了一下,发现还需要引入一个qs模块才能正常使用

this.$http.post('user/login', qs.stringify({
        userName: username,
        password: password
      })).then(function(response) {
        console.log('成功信息!');
      }).catch(function(error) {
        console.log('失败信息!');
      });
上一篇 下一篇

猜你喜欢

热点阅读