axiosに関する内容のまとめ
17495 ワード
axiosの特徴
①基本promiseの非同期ajaxリクエストライブラリ
②ブラウザ側/node側ともに使用可能
③要求/応答ブロック(関数)のサポート
④サポートリクエストキャンセル
⑤要求/応答データ変換
⑥複数リクエストの一括送信
axios常用構文
axios(config) == axios.request(url[,config])
axios(url[,config])
axios.get(url[,config])
axios.post(url[,config])
axios.delete(url[,config])
axios.put(url[,config])
axios.defaults.xxxリクエストデフォルトグローバル構成
axios.interceptors.request.use()リクエストブロッカーの追加
axios.interceptors.response.use()応答ブロックの追加
axios.create([config])新しいaxiosを作成
axios.all(promises):複数の非同期要求を一括実行するために使用される
axios.spread()成功したすべてのデータを受信するコールバック関数を指定する方法
Axios導入とリクエスト
<script src="https://unpkg.com/axios/dist/axios.min.js">script>
function get(){
//axios.get('http://localhost:3000/post?id=1')
axios({
url:'/posts',
param:{
id:1
}
})
.then(response => {
console.log('/posts get',response.data)
})
.catch(error => {
console.log('error',error.message)
})
}
function post(){
// axios.post('http://localhost:3000/post',{"title":"json-server3"})
axios({
url:'/post',
methoda;'post',
data:{"title":"json-server3"}
})
.then(response => {
console.log('/posts post',response.data)
})
}
function put(){ //
// axios.put('http://localhost:3000/post/3',{"title":"json-server3"})
axios({
url:'/post',
methoda;'post',
data:{"title":"json-server3"}
})
.then(response => {
console.log('/posts post',response.data)
})
}
function delete(){ //
// axios.delete('http://localhost:3000/post/3')
axios({
url:'/post/5',
methoda;'delete',
})
.then(response => {
console.log('/posts post',response.data)
})
}
axios create(config)
指定した構成に基づいて新しいaxiosを作成します.つまり、新しいaxiosごとに独自の構成があります.
新しいaxiosの知識は、リクエストをキャンセルする方法と一括送信する方法がなく、他のすべての構文が一致しています.
どうしてこの文法を設計しますか.プロジェクトの一部のインタフェースに必要な構成は他の一部のインタフェースに必要な構成とは異なり、2つの新しいaxiosを作成し、それぞれ独自の構成を持ち、それぞれ異なる要求のインタフェースに適用する.
const instance = axios.create({
baseURL:'http://localhost:3000'
})
// Instance
instance({
url:'/xxx',
method:'post'
})
// Instance
instance.get('/xxx');
ブロッキングおよび実行プロセス
// ( )
axios.interceptors.request.use(
config =>{
console.log('request interceptors1 onResolved()')
return config // config
},
error =>{
console.log('request interceptors1 onRejected()');
return Promise.reject(error);
})
//
axios.interceptors.response.use(
response =>{
console.log('response interceptors2 onResolved()')
return response
},
function(error){
console.log('response interceptors2 onRejected()');
return Promise.reject(error);
})
要求ブロッキングは、要求を送信前に実行する、応答ブロッキングも実行する.then()の前に対応します.
リクエスト・ブロッカーは、後で追加する前に実行し、レスポンス・ブロッカーは、先に追加する前に実行します.
リクエストブロッカーはreturn configを必要とします.書かないと直列の後の操作はundefinedから最後までcatch errorしか得られません.
どうりおうとうブロッキング
リクエストのキャンセル
クリックして現在のリクエストをキャンセル
// cancel null
let cancel;
function get1(){
axios({
url:'/xxx',
cancelToken:new axios.cancelToken((c)=>{ //c
// ,
cancel = c;
})
})
.then(
response =>{
cancel = null;
console.log(' ');
},
error =>{
cancel = null;
console.log(error.message);
}
)
}
// cancel Null
function cencelReq(){
if (typeof cancel === 'function'){
cancel(' ');
}else{
console.log(' ');
}
}