发请求1
axios({method: 'GET', //请求类型url:'路径', //设置请求路径data:{ //设置请求体title: "afafa"author: "afafa"}
}).then(response => {console.log(response);
})
发请求2
axios.request({method: 'GET',url: '路径'
}).then(response => {console.log(response);
})
发请求3
axios.post("路径" , {"body": "afa" //发送请求体"postId": 2
}).then(response => {console.log(response);
})
axios创建实例对象发送请求
const abc = axios.create({baseURL: '路径',timeout: 2000
})
配置axios默认配置
axios.defaults.method = 'GET';
axios.defaults.baseURL = '路径'
axios.defaults.params = {id: 100};
axios.defaults.timeout = 3000;
在发送请求时需要在请求头中添加 Authorization
字段携带 token
,token
的值为 2b58f9a8-7d73-4a9c-b8a2-9f05d6e8e3c7
。
let t = axios.create({headers: {Authorization : `2b58f9a8-7d73-4a9c-b8a2-9f05d6e8e3c7`}})
原生JS发请求
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);
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);}}