axios学习
axios学习
JSON Server安装配置
详见https://www.npmjs.com/package/json-server
-
安装JSON Server
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
json-server --watch db.json -
前往http://localhost:3000/posts/1
{ "id": 1, "title": "json-server", "author": "typicode" }
axios
axios是一个对于浏览器和node.js基于Promise的HTTP客户端
axios基本使用
<script>
const btns = document.querySelectorAll('button')
//第一个
btns[0].onclick = function(){
//发送AJAX请求,返回结果是Promise对象
axios({
//请求类型
method:'GET',
//URL
url:'http://localhost:3000/posts/1'
}).then(value=>{
console.log(value)
})
}
//第二个,发送一个
btns[1].onclick = function(){
//发送AJAX请求,返回结果是Promise对象
axios({
//请求类型
method:'POST',
//URL
url:'http://localhost:3000/posts',
//设置请求体,会自动添加id
data:{
title:"压力马斯内",
author:"lyb"
}
}).then(value=>{
console.log(value)
})
}
//第三个
btns[2].onclick = function(){
//发送AJAX请求,返回结果是Promise对象
axios({
//请求类型
method:'PUT',
//URL
url:'http://localhost:3000/posts/2',
//设置请求体,会自动添加id
data:{
title:"压力马斯内",
author:"先辈"
}
}).then(value=>{
console.log(value)
})
}
//第四个
btns[3].onclick = function(){
//发送AJAX请求,返回结果是Promise对象
axios({
//请求类型
method:'delete',
//URL
url:'http://localhost:3000/posts/3',
}).then(value=>{
console.log(value)
})
}
</script>
axios的API
-
axis.request(config)
//发送GET请求 btns[0].onclick = function(){ axios.request({ method:'GET', url:'http://localhost:3000/comments', }) } -
axios.get(url[,config])
-
axios.delete(url[,config])
-
axios.head(url[,config])
-
axios.options(url[.config])
-
axios.post(url[,data[,config]])
//发送GET请求 btns[1].onclick = function(){ axios.post( 'http://localhost:3000/comments', { "body":"压力马斯内", "postid":2 }) } -
axios.put(url[,data[,config]])
-
axios.patch(url[,data[,config]])
axios的配置对象(config)
{
url: '/user',
//请求类型get,post,put,delete
method: 'get', // default
//url的基础结构,axios会自动将url和baseURL进行结合
baseURL: 'https://some-domain.com/api/',
//对请求的数据进行处理,再将数据向服务器进行发送
transformRequest: [function (data, headers) {
return data;
}],
//对相应的结果进行处理
transformResponse: [function (data) {
return data;
}],
//对请求头信息进行设置
headers: {'X-Requested-With': 'XMLHttpRequest'},
//在url后面添加参数
params: {
ID: 12345
},
//对请求的参数做一个序列化
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
//请求体设置(json形式
data: {
firstName: 'Fred'
},
//请求体设置(url参数字符串形式
data: 'Country=Brasil&City=Belo Horizonte',
//超时时间
timeout: 1000, // default is `0` (no timeout)
//跨域请求时,进行cookie的携带进行设置
withCredentials: false, // default
//对请求识别器进行设置
adapter: function (config) {
/* ... */
},
//对请求的基础验证设置用户名和密码
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
//对响应器结果进行设置
responseType: 'json', // default
//响应编码
responseEncoding: 'utf8', // default
//跨站请求的标识
xsrfCookieName: 'XSRF-TOKEN', // default
//
xsrfHeaderName: 'X-XSRF-TOKEN', // default
//上传回调
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
//下载回调
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
//响应体的最大尺寸
maxContentLength: 2000,
//请求体的最大内容
maxBodyLength: 2000,
//对响应结果的成功进行设置
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
//最大跳转次数
maxRedirects: 5, // default
//设定socket文件的位置
socketPath: null, // default
//客户端信息进行设置
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
//设置代理
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
//对AJAX请求进行取消的设置
cancelToken: new CancelToken(function (cancel) {
}),
//响应结果是否解压
decompress: true // default
signal: new AbortController().signal,
insecureHTTPParser: undefined // default
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
}
}
axios的默认配置
//默认配置
axios.defaults.method = 'GET' //设置默认请求类型
axios.defaults.baseURL = 'http://localhost:3000'//设置基础的URL
//发送GET请求
btns[0].onclick = function(){
//发送AJAX请求,返回结果是Promise对象
axios({
//请求类型
method:'GET',
//URL
url:'/posts'
}).then(value=>{
console.log(value)
})
}
axios创建实例对象
//创建实例对象
const another = axios.create({
baseURL:'https://api.apiopen.top',
timeout:2000
});
//现在该实例对象几乎和axios一摸一样
another({
url:'/getJoke',
}).then(value=>{
console.log(value);
})
//还可以如下
another.get('/getJoke').then(value=>{
console.log(value.data)
})
axios的拦截器
请求拦截器是后进先执行
响应拦截器是先进先执行
<script>
//设置请求拦截器
//config就是配置对象
axios.interceptors.request.use(function (config) {
//可以修改config的配置
config.params = {a:100}
console.log('请求拦截器成功')
return config;
}, function (error) {
console.log('请求拦截器失败')
return Promise.reject(error);
});
//设置响应拦截器
//response就是响应结果
axios.interceptors.response.use(function (response) {
console.log('响应拦截器成功')
return response;
}, function (error) {
console.log('响应拦截器失败')
return Promise.reject(error);
});
</script>
axios取消请求
<script>
btns = document.querySelectorAll('button');
//2.声明全局变量
let cancel = null;
btns[0].onclick = function(){
if(cancel!=null){
cancel()
}
axios({
method:'GET',
url:'http://localhost:3000/posts',
//取消请求
//1.添加配置对象的属性
cancelToken:new axios.CancelToken(function(c){
//将c的值赋值给cancel
cancel = c;
})
}).then(response=>{
console.log(response)
cancel = null
})
}
btns[1].onclick = function(){
//3.取消请求
cancel();
}
</script>

浙公网安备 33010602011771号