プロジェクトでネットワークリクエストを使用する必要がある場合、ネイティブajax(XMLHttpRequestに基づく)、jQuery-Ajax、vue-resource(廃止)、そして現在のaxiosから選択する方法はたくさんあります。
axiosの利点は次のとおりです。
-
ブラウザでXMLHttpRequestリクエストを送信します。
-
node.jsでhttpリクエストを送信します。
-
Promiseをサポートします。
-
要求と応答を傍受できます。
-
変換の要求と応答。
Axiosリクエストメソッド:
-
axios(config)
-
axios.request(config)
-
axios.get(url、config)
-
axios.delete(url、config)
-
axios.head(url、config)
-
axios.post(url、data、config)
-
axios.put(url、data、config)
-
axios.patch(url、data、config)
Axiosは同時リクエストを送信します。.all()を使用して同時リクエストをマージできます
axios.all([ axios( 第一次网络请求 )
,axios( 第二次网络请求 )]
)
.then(results=>{
//结果处理语句
})
返される結果は配列です。これは、前のn個のリクエストの結果を組み合わせた配列です。
.spread()を使用して、結果を分割できます。
axios.all([axios( //第一次网络请求 ),axios( //第二次网络请求 )])
.then(axios.spread( (res1,res2) => {
console.log(res1);
console.log(res2)
})
)
axiosのグローバル構成:
axios.defaults.baseURL = "http://127.1.1.1"
axios.defaults.timeout = 1000
一般的な構成オプション:
-
リクエストアドレス:url: '/ user'
-
リクエストタイプ:メソッド: 'get'
-
リクエストルートパス:baseURL: ' http://127.1.1.1 '
-
リクエスト前のデータ処理:transformRequest:[function(data){}]
-
リクエスト後のデータ処理:transformResponse:[function(data){}]
-
カスタムリクエストヘッダー:headers:{'X-Requested-With': 'XMLHttpRequest'}
-
URLクエリオブジェクト:params:{id:12}
-
クエリオブジェクトのシリアル化関数:paramsSerializer:function(params){}
-
リクエスト本文:データ:{キー: 'xx'}
-
タイムアウト設定ms:タイムアウト:1000
-
ドメイン間でトークンを持ち込むかどうか:withCredentials:false
-
カスタム処理要求:adapter:function(resolve、reject、config){}
-
本人確認情報:auth:{uname: 'xiaoming'、pwd: '12'}
-
応答データ形式:json / blob / document / arraybuffer / text / Steam responseType: 'json'
axiosインスタンス
axiosの複数のインスタンスを作成します。インスタンスでは、このインスタンスのデフォルトの構成情報を作成できます。特定のインスタンスが使用されると、そのインスタンスの構成がトリガーされます。
インスタンスを作成します。
const instance = axios.create({ baseURL:'http://127.1.1.1', timeout:1000 })
使用事例:
instance({ url:'/user' })
Axiosパッケージフォーム1:
import axios from 'axios'
export function request( config, success, fail ){
const instance = axios.create({ baseURL:'http://127.1.1.1', timeout: 1000 })
instance(config)
.then( res=>{
success(res)
})
.catch( err=>{
fail(err)
})
}
コンポーネント内:
import { request } from './request.js'
request( { url:'/user' },
res => { console.log(res) },
err=>{console.log(err) }
)
Axiosパッケージフォーム2:
export function request(config){
return new Promise(resolve, reject)=>{
const instance = axios.create({
baseURL: 'http://127.1.1.1',
timeout: 1000
})
instance(config).then(res=>{ resolve(res) })
.catch(err=>{ reject(err) })
})
}
コンポーネント内:
request({ url:'/home' }).then(res=>{ console.log(res) })
.catch(err=>{ console.log(err) })
Axiosパッケージフォーム3:
axiosインスタンス自体はaxiosPromiseであるため、別のPromiseを使用してインスタンスをカプセル化せずに、このインスタンスを直接返すことができます。
export function request(config){
const instance = axios.create({
baseURL: 'http://127.1.1.1',
timeout: 1000
})
return instance(config)
}
コンポーネント内:
request({ url:'/home' }).then(res=>{ console.log(res) })
.catch(err=>{ console.log(err) })