http POST请求键值对参数以及json参数

在使用post进行http请求时有2种参数类型,要根据接口切换不同的参数格式

键值对格式参数一般表现为:username=123&password=123

json格式参数一般表现为:{"username":"123","password":"123"}

以下示例代码为vue代码:

发送键值对参数:

首先npm下载axios和qs(这里是借助qs来进行键值对处理)

npm install axios --save

npm install qs--save
import axios from 'axios';
import qs from "qs";

//post键值对格式
    post(url, data) {
        return axios({
            method: "post",
            url: url,
            data: qs.stringify(data),
            timeout: 30000,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            },
        })
            .then(response => {
                console.log(response);//状态码处理
            })
            .then(res => {
                console.log(res);//异常处理
            });
    },

发送json参数:

json格式参数不需要qs进行处理,直接传入对象格式的数据

//post json格式
    postJson(url, data) {
        return axios({
            method: "post",
            url: url,
            data: data,
            timeout: 30000,
            headers: {
                "Content-Type": "application/json; charset=UTF-8",
            },
        })
            .then(response => {
                return checkStatus(response);
            })
            .then(res => {
                return checkCode(res);
            });
    },

猜你喜欢

转载自blog.csdn.net/Lc_style/article/details/84861790