GET请求
axios.get("http://127.0.0.1:8090/data").then(function (ret){ console.log(ret); console.log(ret.data); console.log(ret.status); console.log(ret.statusText) })
|
GET传值
方法一
axios.get("http://127.0.0.1:8090/data3?id=13").then(function (ret){ console.log("25: "+ret.data); })
|
方法二
axios.get("http://127.0.0.1:8090/data3",{params:{ id:937 }}).then(function (ret){ console.log("32: "+ret.data); })
|
POST传值
方法一
axios.post("http://127.0.0.1:8090/data4",{ user:'李四', pwd:'12345' }).then(function(ret){ console.log("45: "+ret.data); })
|
方法二
var params=new URLSearchParams(); params.append('user','李思2'); params.append('pwd','xyh1212'); axios.post("http://127.0.0.1:8090/data4",params).then(function(ret){ console.log("53: "+ret.data); })
|
delete路径传值
axios.delete("http://127.0.0.1:8090/data5/id=2022").then(function(re){ console.log("37: "+re.data); })
|
Put请求发送数据
var cf={name:"李四",age:19}; axios.put("http://127.0.0.1:8090/data6",{ name:'历史', age:89 }).then(function(re){ console.log("62: "+re.data.name+" "+re.data.age); })
|
服务器发送JSON
axios.get("http://127.0.0.1:8090/json").then(function(re){ console.log(re); console.log("69:"+ re.data.username+" "+re.data.age) })
|
优化URL
axios.defaults.baseURL="http://127.0.0.1:8090";
axios.get("json").then(function(re){ console.log(re); console.log("16:"+ re.data.username+" "+re.data.age) })
|
添加请求头
axios.defaults.headers['token']="JWT Token1728y871271tt163tt131738118"; axios.get("json").then(function(re){ console.log(re); console.log("23:"+ re.data.username+" "+re.data.age) })
|
NodeJS获取请求头
app.get("/json",function (req,res){ res.json({ username:'李四', age:19, sex:'男' }) console.log("56:"+req.headers.token); })
|
拦截器
请求拦截器
每个地址都要经过这个拦截器
axios.defaults.baseURL="http://127.0.0.1:8090"
axios.interceptors.request.use(function (config){ console.log(config); config.headers.token = "JWT Token1728y871271tt163tt131738118"; console.log("URL:"+config.url); return config; },function (er){ console.log(er); }) axios.get("json").then(function(re){ console.log(re); console.log("33:"+ re.data.username+" "+re.data.age) })
|
响应拦截器
默认数据返回是在JSON中 可以在响应中返回改变后的数据 直接返回data里面的数据
axios.interceptors.response.use(function (res){ console.log(res); return res.data; },function (er){ console.log(er); })
axios.get('data').then(function (re){ console.log("50: "+re); })
|
配合await使用
axios.defaults.baseURL="http://127.0.0.1:8090";
axios.interceptors.response.use(function (res){ return res.data; },function (error){ console.log(error); })
async function test(){ let t1=await axios.get("data") console.log(t1); let t2=await axios.get("data2"); console.log(t2); } test();
|
抓取异常
axios.get('data').then(function (re){ console.log("50: "+re); }).catch(function(er){ console.log(er); })
|
创建实例
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
instance.get('xx').then((res)=>{ })
|