1.axios
基本的な使用法
get
そして、delete
パラメータを渡すように要求します。
- 従来の形式:パラメータ
url
を次?
の形式で渡します
restful
フォーム:フォームを介してparams
パラメータを渡します
post
そして、put
パラメータを渡すように要求します。
- オプションを介してパラメータを渡す
- することで
URLSearchParams
パラメータを渡します
# 1. 发送get 请求
axios.get('http://localhost:3000/adata').then(function(ret){
# 拿到 ret 是一个对象 所有的对象都存在 ret 的data 属性里面
console.log(ret)
})
# 2. get 请求传递参数
# 2.1 通过传统的url 以 ? 的形式传递参数
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
# 2.2 restful 形式传递参数
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
# 2.3 通过params 形式传递参数
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios delete 请求传参 传参的形式和 get 请求一样
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4 axios 的 post 请求
# 4.1 通过选项传递参数
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2 通过 URLSearchParams 传递参数
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
#5 axios put 请求传参 和 post 请求一样
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
2.axios
グローバル構成
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 2500;
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
3.axios
インターセプター
- リクエストインターセプターリクエストインターセプター
の役割は、リクエストが送信される前にいくつかの操作を実行することです。たとえば、各リクエスト本文に追加すると、token
一律に処理されます。将来の変更は非常に簡単です。
- 一部の操作では
、アクセス応答での応答ブロッカー応答インターセプターの役割が受信されます。たとえば、サーバーがログインステータスが無効であり、再度ログインする必要があることを返した場合、ログインページにジャンプします。
axios.interceptors.request.use(function(config) {
console.log(config.url);
config.headers.mytoken = 'nihao';
return config;
}, function(err) {
console.log(err);
});
axios.interceptors.response.use(function(res) {
var data = res.data;
return data;
}, function(err) {
console.log(err);
});