• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • axios 发送数据请求的方式

    数据传送:类型与编码

    Content-Type

    Content-Type编码类型,是指httphttps发送信息至服务器时的内容编码类型,用于表明发送数据流的类型,服务器根据编码类型使用特定的解析方式,获取数据流中的数据。常用的Content-Type有如下:

    • text/html,text/plain,text/css,text/javascript,image/jpeg,image/png,image/gif等常见的页面资源类型。
    • application/x-www-form-urlencoded, multipart/form-data,application/json,application/xml,这四个是表单提交或上传文件的常用的资源类型。

    axios 请求

    methodContent-Type编码方式
    postapplication/x-www-form-urlencodedformdata
    postmultipart/form-dataformdata
    postapplication/jsonrequest payload
    getapplication/jsonQuery String Parameters

    Query String Parameters

    当发起一次get请求时,参数会以url string 形式进行传递。即?后的字符串则为其请求参数,并以&作为分隔符。

    axios.get('https://api.example.com/topiclist?cid=2');
    

    Request Payload

    Request Payload更准确的说是http requestpayload body,对应请求体。一般用在数据通过POST请求或者PUT请求。

    axios 默认Content-Type:application/json,以json形式将数据发送给服务器。

    let data = {"name": "123", "val": "456"};
    axios.post('https://api.example.com/topic/save', data)
    

    contentType:"application/json",是一种文本类型,表示json 格式的文本。在数据传输过程中,json 数据是以文本的形式传递。
    json 格式:{"key":"value"},键值对并且带有双引号

    Form Data

    编码方式Form Data,特点是:对于表单字段以name/value值对形式传递,对于上传文件,以二进制编码方式传送。

    var formData = new FormData();
    formData.append("email","56789@qq.com");
    formData.append("password",123456);
    
    axios.post('https://api.example.com/login', formData)
    

    axios 请求数据的方式

    axios 默认设置:

    axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    
    • 当每个具体的向后端服务器发送的请求,非post请求的时候,比如:get、put、delete、patch等请求,若没有特别设置Content-Type的时候,其类型为application/json。若单独设置的时候,以最后的具体设置为准。
    • 当每个具体的向后端服务器发送的请求,是post请求的时候,若没有特别设置Content-Type的时候,其类型为application/x-www-form-urlencoded。若单独设置的时候,以最后的具体设置为准。
    • 在 axios 封装的时候,没有设置此类型,那么默认也是此类型。所以在封装的时候,可以不写以上设置,因为它是默认的设置。

    在实际开发过程中,根据开发多用的类型来设置。比如,在 axios 封装的时候,跟后端开发的程序员,约定绝大多数情况下使用的JSON数据,那么设定:

    axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
    axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
    
    前后端分离模式下的开发,多用携带token数据保证数据交互安全。也有携带cookie数据的,在跨域资源共享下(CORS模式),这些携带身份验证的方式,都会触发【预检请求】options请求。另外,当Content-Type:application/json;(以 json 数据交互),也会触发【预检请求】options请求。所以,在跨域资源共享下(CORS模式),可以设置Access-Control-Max-Age请求缓存来减少【预检请求】。

    get 请求

    对于 axios 的请求方式get,Content-Type:application/json,编码方式:Query String Parameters,是通过 url 方式来传参数。例如:https://api.example.com/novellist?cid=1。即?后的字符串则为其请求参数,并以&作为分隔符。

    import axios from 'axios';
    
    axios.get('https://api.example.com/novellist?cid=1');
    
    //或者
    axios({
        method:'get',
        url:'https://api.example.com/novellist?cid=1',
    })
    

    params选项,来传递参数,是相同的效果:

    import axios from 'axios';
    
    axios({
        method:'get',
        url:'https://api.example.com/novellist',
        params:{
            cid:1
        }
    })
    

    paramsSerializer选项,是对params选项进行序列化:

    import axios from 'axios';
    import Qs from 'qs';
    
    axios({
        method:'get',
        url:'https://api.example.com/novellist',
        params:{
            cid:1
        },
        paramsSerializer:function (params) {
            return Qs.stringify(params)
        },
    })
    

    以上几种方式,都是相同的请求 url 网址:https://api.example.com/novellist?cid=1

    post 请求

    axios 在 post 请求方式下,有点复杂,比 get 方式复杂一点。需要注意两个方面:

    1. HTTP 请求中 header 头部中,Content-Type设定。
    2. 请求中,所发送的数据格式,axios 设置中,有两个选项data选项,transformRequest选项。

    方式一:普通表单之 json 数据

    axios 默认设置下,发送 post 请求,提交普通表单。以账号密码登录为例子:

    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    
    axios.post('https://api.example.com/login',{
          data:{
            email: '567899@qq.com',
    	password: '123456',
          },
        }
    })
    
    或者
    
    axios({
        method:'post',
        url:'https://api.example.com/login',
        data:{
            email: '567899@qq.com',
    	password: '123456',
        }
    })
    

    Content-Type:application/json;

    我们看到Content-Type:application/json;,而非默认设置的Content-Type: application/x-www-form-urlencoded;。出现这样的变化,是因为data选项,保存的是objec对象,发送请求过程会被以、JSON格式发送,既然发送的是JSON数据,那么 axios 会自动使用 HTTP 请求 header 中,Content-Type: application/json;

    若要保证是普通表单数据,Content-Type:application/x-www-form-urlencoded;,而非JSON数据,还应该使用transformRequest选项。对于后端这两种不同的数据类型,接收方式不同。

    当然以 post 方式来发送JSON表单数据,也是正常的传送方式,也是能被后端处理的。需要与开发后端程序员约定好。个人提倡:前后端都以JSON数据来交互。出于代码洁癖,axios 的 post 默认设置可以修改为(也可以不修改,毕竟 axios 会自动调整):

    axios.defaults.headers.post['Content-Type'] = 'application/application/json;charset=UTF-8';
    

    注意事项:

    • 提交普通表单的时候,Content-Type是:application/x-www-form-urlencoded;。若表单中含有上传文件的时候,Content-Type应该为:multipart/form-data
    • 配置中的data选项,是objec对象,非 json 数据格式。即使手工改写成 json 数据格式(带双引号的键值对),是多余的行为,axios 在 HTTP 传送过程中,会把它们转化为标准 JSON 数据格式。
    标准写法
    axios({
        method:'post',
        url:'https://api.example.com/login',
        data:{
            email: '567899@qq.com',
    	password: '123456',
        }
    })
    
    与此相同的效果,JSON 格式数据。没有必要如此,因为 axios 会自动转化。
    axios({
        method:'post',
        url:'https://api.example.com/login',
        data:{
            "email": '567899@qq.com',
    	"password": '123456',
        }
    })
    

    以标准 json 数据格式,post 数据

    若想生成标准的 json 格式数据,需要在transformRequest选项中,格式化数据。

    axios.post('https://api.example.com/login',{
          data:{
             email: '567899@qq.com',
    	 password: '123456',
          },
          transformRequest: [
            (data) => {
              return JSON.stringify(data);
            },
          ],
        }
    })
    
    
    或者
    axios({
        method:'post',
        url:'https://api.example.com/login',
        data:{
            email: '567899@qq.com',
    	password: '123456',
        }
        transformRequest: [
            (data) => {
              return JSON.stringify(data);
            },
        ],
    })
    

    方式二:普通表单之 Form Data 数据

    transformRequest选项,对data选项中的对象,进行转化。转化成为Form Data(字段为键值对,例如:email=567899@qq.com&password=123456)数据结构。

    import axios from 'axios';
    import Qs from 'qs';
    
    
    axios({
        method:'post',
        url:'https://api.example.com/login',
        headers:{
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          },
        data:{
            email: '567899@qq.com',
    	password: '123456',
        },
        transformRequest: [
            (data) => {
              return Qs.stringify(data);
            },
        ],
    })
    

    方式三:上传表单之 Form Data 数据

    表单数据中,包含有上传图片、上传视频音频等。此类上传表单,只能是Content-Typemultipart/form-data,以Form Data编码方式传送数据。

    import axios from 'axios';
    
    let formData = new FormData();
    formData.append('file', file);
    
    axios.post('https://api.example.com/thumbnail/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data;charset=UTF-8',
        },
    })
    
    
    或者
    axios({
        method:'post',
        url:'https://api.example.com/thumbnail/upload',
        data:formData,
        headers: {
            'Content-Type': 'multipart/form-data;charset=UTF-8',
        },
    })