【http请求库】Axios的使用

axios是一个轻量的HTTP请求库,可以用在 浏览器 或 node.js 中,目前是 VUE 官方推荐的请求库。

引入axios

1、在 html 中引入

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>

2、在 node.js 中引入

npm install axios --save-dev

GET 方法

axios.get("url", {
    params: {
        key: value
    },
    headers: {
        key: value
    }
}).then(res => {
	// 请求成功
    console.log("请求到的数据为:" + res.data);
    res.headers; // response 的 headers
    res.status; // 状态码
    res.statusText; // 状态信息
    res.config; // 配置信息
    res.request; // request
}).catch(error => {
	// 请求失败
    console.log(error);
});


POST 方法

axios 的 POST 方法默认类型是“application/x-www-form-urlencoded”,所以我们首先要先将 json 序列化:

{key1: value1, key2: value2} 变成 key1=value1&key2=value2 的形式。

// json序列化函数
function mStringify(obj) {
    var temp = "";
    for (var key in obj) {
        temp += key + "=" + obj[key] + "&";
    }
    return temp.substring(0, te.length - 1);
}
var data = {
	key: value
};

axios.post("url", mStringify(data), {
    headers: {
    	key: value
    }
}).then(res => {
	// 请求成功
   
    console.log("请求到的数据为:" + res.data);
    res.headers; // response 的 headers
    res.status; // 状态码
    res.statusText; // 状态信息
    res.config; // 配置信息
    res.request; // request
}).catch(error => {
	// 请求失败
    console.log(error);
});

猜你喜欢

转载自blog.csdn.net/qq_34802028/article/details/107294690