豪翔天下

Change My World by Program

0%

axios网络请求

基本请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 基本请求方式
axios({
method: 'post',
url: '/user/123',
headers: {},
params: {},
data: {}, // POST的data
timeout: 0, // 超时时间,默认为0,表示不超时
responseType: 'json', // 默认接收JSON格式的响应
maxRedirects: 5, // 默认重试次数为5
onUploadProgress: function (progressEvent) {}, // 上传前执行
onDownloadProgress: function (progressEvent) {}, // 下载前执行
validateStatus: function (status) {
return status >= 200 && status < 500 // 定义哪些http状态不会抛错
}
})
.then((rersponse: AxiosResponse) => {})
.catch((error: AxiosError) => {
console.log(error.response.status) // 获取返回状态码
console.log(error.message) // 获取错误信息
console.log(JSON.parse(error.request.response).message) // 另外一种错误相应的格式
console.log(`${error.config.baseURL}${error.config.url}`) // 获取请求的URL
})

// 创建一个可复用的client
const client = axios.create({
baseURL: '',
headers: {}
})

Axios跨域请求

1
2
3
4
axios.get('/user', {
withCredentials: true, // 跨域请求带上认证信息
params: {}
}).then(...).catch(...)

XSRF请求

1
2
3
axios({
xsrfCookieName: 'XSRF-TOKEN' // 带上这个参数能自动从cookie里面获取xsrf的token置入header头
})

中间件/hook/beforerequest/afterresponpse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
axios.interceptors.request.use((config) => {
config.headers = {....};
config.headers['request-startTime'] = new Date().getTime();
return config;
});

axios.interceptors.response.use(async (res) => {
console.log(res.data, res.request.path, res.request._url);
console.log(new Date().getTime() - (Number(res?.config?.headers?.['request-startTime']) || 0)); // 获取请求的耗时可以这样做
await new Promise((r) => setTimeout(r, 800));
return res;
}, (error) => {
console.log(error.response.status);
});

取消Axios的HTTP请求

1
2
3
4
5
6
const cancelTokenSource = axios.CancelToken.source();
axios.get('/xxx', {
cancelToken: cancelTokenSource.token
}).then(...).catch(...)

cancelTokenSource..cancel // 取消请求

Axios设置代理

1
2
3
4
5
6
7
8
9
10
11
axios({
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'haofly',
password: 'xxx'
}
}
})

Axios并发请求

1
2
3
4
5
6
7
8
9
function getUserAccount() { return axios.get('/user/12345') }

function getUserPermissions() { return axios.get('/user/12345/permissions') }

Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});

Axios Stream 请求

  • 注意nginx的location也需要添加配置proxy_buffering off; fastcgi_buffering off;
1
2
3
4
axios({
url: '',
responseType: 'stream'
})

Axios下载文件

1
2
3
4
5
6
7
8
9
10
11
12
axios.get(url, responseType: 'blob').then(response => {
console.log(response.data.split('\n') // 下载csv文件能够直接读取
})

axios({
method: 'get',
url: 'http://haofly.net',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('aaa.jpg'))
});

Troubleshooting

坚持原创技术分享,谢谢支持

欢迎关注我的其它发布渠道