社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1,请求行
2,请求头
contenttype是指定浏览器对请求体的解析方式
3,请求体
基于promise的http客户端
npm install -g json-server
创建db.json文件
文件写入
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
json-server --watch db.json
var buttons = document.querySelectorAll("div button");
buttons[0].onclick=function () {
axios({
method:"get",
url:"http://localhost:3000/posts/1"
}).then((response)=>{
console.log(response)
},()=>{})
};
buttons[1].onclick=function () {
axios({
method:"post",
url:"http://localhost:3000/posts",
data:{
title:"ss", //post的参数传递
name:"sm"
}
}).then((response)=>{
console.log(response)
},()=>{})
};
buttons[2].onclick=function () {
axios({
method:"put",
url:"http://localhost:3000/posts/2",
data:{
title:"ss", //put指定要更新的参数
author:"sm"
}
}).then((response)=>{
console.log(response)
},()=>{})
};
buttons[3].onclick=function () {
axios({
method:"delete",
url:"http://localhost:3000/posts/2",
}).then((response)=>{
console.log(response)
},()=>{})
}
axios.defaults.method="get";
axios.defaults.baseURL="http://localhost:3000";
// axios.defaults.timeout=3000;
var buttons = document.querySelectorAll("div button");
buttons[0].onclick=function () {
axios({
url:"/posts/1"
}).then((response)=>{
console.log(response)
},(err)=>{console.log(err)})
};
多个域名的话,创建axios实例
var axios1 = axios.create({
method:"get",
baseURL:"http://localhost:3000",
timeout:3000
});
var buttons = document.querySelectorAll("div button");
buttons[0].onclick=function () {
axios1({
url:"/posts/1"
}).then((response)=>{
console.log(response)
},(err)=>{console.log(err)})
};
var axios1 = axios.create({
method:"get",
baseURL:"http://localhost:3000",
timeout:3000
});
let cancelToken=null;
var buttons = document.querySelectorAll("div button");
buttons[0].onclick=function () {
if (cancelToken!=null){
cancelToken(); //取消上次请求
}
axios1({
url:"/posts/1",
cancelToken:new axios.CancelToken(function (cancel) {
cancelToken=cancel;
})
}).then((response)=>{
cancelToken=null;
console.log(response)
},(err)=>{console.log(err)})
};
buttons[1].onclick=function () {
cancelToken();
};
调create方法创建axios
request调dispathrequest调adapter
先运行请求拦截器二号,在运行请求拦截器一号,在运行响应拦截器一号,响应拦截器二号,最后运行用户的自定义回调
use将函数回调保存在request的handers属性上
axios或axios.create调createinstance创建对象,由request发起请求,request内部有interceptor拦截器,通过后由dispatchRequest发送请求。结果回来后由响应拦截器处理,最后是用户指定的成功或失败的回调执行
响应拦截器
data,status,statusText,headers,config,request
参数限制
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!