Ajax:异步网络请求,可以让页面无刷新的请求数据。实现ajax的方式有jQuery封装的ajax、原生的XMLHttoRequest、axios
Axios是一个基于promise的HTTP库,本质上还是对原生XMLHttpRequest的封装,可以用在浏览器和node.js中。在服务器端它使用原生node.js http模块,在客户端(浏览端)使用XMLHttpRequests
一、具备的特点
- 从浏览器创建XMLHttpRequest
- 从 node.js 创建http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
二、安装
npm install axios
三、请求
1.发起get请求(axios.get())
//为给定ID的user创建请求
import axios from "axios";
axios.defaults.baseURL = 'https://v1.hitokoto.cn/'
axios.get('user?ID=12345')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error)
})
//可配置参数的方式
import axios from "axios";
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error)
})
2.发起post请求(axios.post())
import axios from 'axios'
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(response){
console.log(response);
}
.catch(function (error){
console.log(error);
});
3.发起多个并发请求(axios.all())
(1) 通过axios.all(iterable)可实现发送多个请求,参数不一定是数组,但必须是iterable接口,函数返回一个数组。
function getUserAccount(){
return axios.get('/user/12345');
}
function getUserPermissions(){
return axios.get('user/12345/premissions');
}
axios.all([getUserAccount(),getUserPermissions()])
.then(function(result){
const acct=results[0];
const perm=results[1];
})
(2)axios.spread(callback)可用于将结果数组展开
function getUserAccount(){
return axios.get('/user/12345');
}
function getUserPermissions(){
return axios.get('user/12345/premissions');
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread((res1,res2)=>{
console.los(res1,res2);
}))
.catch(err=>console.log(err))
四、Axios API
可以通过向axios传递相关配置来创建请求
axios的请求方式:
- axios(config)
- axios.request(config)
- axios.get(url [,config])
- axios.post(url [,data[,config]])
- axios.put(url [,data[,config]])
- axios.delete(url [,config])
- axios.patch(url [,data[,config]])
- axios.head(url [,config])
1.axios(config)
可通过设置一些属性来发送请求
(1)发送一个post请求
axios({
method:'post', //请求方式,默认get请求
url:'/user/12345', //地址
data:{ //参数
firstName:'Fred',
lastName:'Flintstone'
}
});
(2)在node.js用get请求获取远程图片
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
(3)发送一个get请求(默认请求方式)
axios('/user/12345');
五、创建一个实例(axios.create([config]))
const instance=axios.create({
baseURL:'http:''localhost:3000/api/products'.
timeout:1000,
headers:{'X-Custom-Header':'foobar'}
});
//instance的使用
instance.get('/user',{
params:{ID:12345}
})
.then(res=>console.log(res))
.catch(err=>console.log(err))
实例方法
以下是可用的实例方法。指定的配置将与实例的配置合并。
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])
六、config配置
{
//服务器地址
url:'/user',
//请求方式,默认get
method:'get',
//如果url不是绝对地址,则会设置baseURL便于为axios实例的方法传递相对URL
baseURL:'http://localhost:3000/',
//tansformRequest允许在向服务器发送前,修改请求数据
//只能用在'put','post'和'patch'这几个请求方法
//后面的数组中的函数必须返回一个字符串,或ArrayBuffer,或Stream
transformRequest:[function(data){
//对data进行任意转换处理
return data;
}],
//transformResponse在传递给then/catch前,允许修改响应数据
transformResponse:[function(data){
//对接收的data进行任意转换处理
return data;
}],
//自定义请求头
headers;{'X-Requested-With':'XMLHttpRequest'},
//params是与请求一起发送的URL参数
params:{
ID:12345
},
//序列化params (可选)
paramsSerializer:function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})
},
// data是请求时作为请求体的数据
// 仅适用'post','put','delete'和'patch'请求方法
// 在没有设置transformRequest时,则必须是以下类型之一:
// string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams
// 浏览器专属:FormData,File,Blob
// Node专属:Stream,Buffer
data:{
firstName:'Fred'
},
// timeout指定请求的时间,单位毫秒,如果请求时间超过timeout的设定值,请求中断
timeout: 1000, // 默认值是 `0` (永不超时)
//跨域请求是否需要证明
widthCredentials:false,//默认false
//adapter适配器,允许自定义处理请求,返回一个promise
adapter:function(config){...}
//auth表明http基础的认证应该被使用,并提供证书
auth:{
username:'simon',
password:'123456',
},
//服务器返回的数据类型(json/blob/document/arraybuffer/text/stream),默认json
responseType:'json',
//解码响应的编码(Node,js专属),默认utf8
responseEncoding:'utf8',
// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值
// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
// `onUploadProgress` 允许为上传处理进度事件,浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `onDownloadProgress` 允许为下载处理进度事件, 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},
// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值
// `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // default
// `proxy` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// 取消请求
cancelToken: new CancelToken(function (cancel) {
}),
}
七、响应结构
{
// `data` 由服务器提供的响应
data: {},
// 服务器返回的 HTTP 状态码
status: 200,
// 服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 是服务器响应头
// 所有的 header 名称都是小写,而且可以使用方括号语法访问
// 例如: `response.headers['content-type']`
headers: {},
// config是axios进行的设置,目的是为了请求(request)
config: {},
// `request` 是生成此响应的请求
// 在node.js中它是最后一个ClientRequest实例 (in redirects),
// 在浏览器中则是 XMLHttpRequest 实例
request: {}
}
//使用then后,response中将包含上述信息
axios.get('/user/12345')
.then(response={
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});