美文网首页
第二篇:axios请求的的四种格式

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

作者: 落花夕拾 | 来源:发表于2019-10-29 17:06 被阅读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)
});

相关文章

  • 关于http请求

    axios的post请求:1.formdata数据格式 2.json数据格式 axios的get请求:

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

    备注:四种方式任选一种即可。 注意: 默认情况下,axios将JavaScript对象序列化为JSON。 要改为以...

  • post

    axios默认的请求格式是 application/jsonajax默认的请求格式是 application/x-...

  • 前端Vue axios FormData上传图片相关问题

    1.Vue axios 默认是 Payload格式数据请求,后端全部接口都需要 Form Data的格式数据请求2...

  • 2020-01-14

    (转载)Vue使用axios,设置axios请求格式为form-data 原文链接:https://www.jia...

  • Axios POST FormData格式请求

    目录 前言 使用axios进行post请求的时候,默认是传递的json格式的参数,当接口需要FormData格式的...

  • vue数据请求方式

    数据请求 1.Axios :基于promise,可以自动将数据转换为json格式,可以拦截ajax请求,拦截响应 ...

  • axios发送formdata请求

    axios 默认是 Payload格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我...

  • axios post formdata请求

    axios 默认是 Payload格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我...

  • axios 代理服务器

    npm i axios 下载 import axios from 'axios' 引入 发送请求axios请求 跨...

网友评论

      本文标题:第二篇:axios请求的的四种格式

      本文链接:https://www.haomeiwen.com/subject/vxygvctx.html