发请求1
javascript
axios({
method: 'GET', //请求类型
url:'路径', //设置请求路径
data:{ //设置请求体
title: "afafa"
author: "afafa"
}
}).then(response => {
console.log(response);
})
发请求2
javascript
axios.request({
method: 'GET',
url: '路径'
}).then(response => {
console.log(response);
})
发请求3
javascript
axios.post("路径" , {
"body": "afa" //发送请求体
"postId": 2
}).then(response => {
console.log(response);
})
axios创建实例对象发送请求
javascript
const abc = axios.create({
baseURL: '路径',
timeout: 2000
})
配置axios默认配置
javascript
axios.defaults.method = 'GET';
axios.defaults.baseURL = '路径'
axios.defaults.params = {id: 100};
axios.defaults.timeout = 3000;
在发送请求时需要在请求头中添加 Authorization
字段携带 token
,token
的值为 2b58f9a8-7d73-4a9c-b8a2-9f05d6e8e3c7
。
javascript
let t = axios.create({
headers: {
Authorization : `2b58f9a8-7d73-4a9c-b8a2-9f05d6e8e3c7`
}
})
原生JS发请求
javascript
var xhr = new XMLHttpRequest(); //创建发送请求的对象
xhr.onreadystatechange = await function(){
if(xhr.readyState === 4){
console.log("服务器的响应结果已经全部收到")
const obj = JSON.parse(xhr.responseText);
console.log(obj)
}
}
xhr.open("GET" , MockURL);
xhr.send(null);
javascript
async function fetchData() {
try {
const response = await fetch(MockURL);
if (!response.ok) {
throw new Error('Request failed');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}