第二篇:axios请求的的四种格式

2019-10-29  本文已影响0人  落花夕拾

1、请求地址和请求参数以字符串拼接一起传

get:请求
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

post:请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


2、get请求后面带上params形式的json形式的参数;post请求则是把params改成data即可

get:请求
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });


post:请求
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

3、使用async 、await形式
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

4、也可以通过method来区分请求形式
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

备注:四种方式任选一种即可。

注意:

默认情况下,axios将JavaScript对象序列化为JSON。 要改为以application / x-www-form-urlencoded格式发送数据,可以使用以下选项之一。
引入qs包
首先qs是一个npm仓库所管理的包,

npm install qs

使用

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

或
let data = {
     firstName: 'Fred',
    lastName: 'Flintstone'
}
axios({
  method: 'post',
  url: '/user/12345',
  data:qs.stringify(data)
});

上一篇 下一篇

猜你喜欢

热点阅读