vue 2.0のaxios使用詳細


axios
PromiseベースのHTTP要求クライアントは、ブラウザとnode.jsで同時に使用できます.
機能の特性
  • ブラウザから送信 XMLHttp Requests 請求
  • node.jsで送信 http要請
  • サポート Promise API
  • 傍受要求と応答
  • 変換要求と応答データ
  • JSONデータ自動変換
  • クライアントサポート保護安全免除 XSRF 攻撃
  • ブラウザのサポート
    インストール
    bowerを使う:
    
       npm:
     
    
      
    一つ送ります  GET 要求
    // Make a request for a user with a given ID
    axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); 
    一つ送ります  POST 要求
    axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); 
    複数の同時要求を送信する
    function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); 
    axios API
    渡すことで  axios(config)
    // Send a POST request
    axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); 
    axios(url[,config])
    // Sned a GET request (default method)
    axios('/user/12345'); 
    要求方法のエイリアス
    便利さのために、私たちはすべてのサポートの要請方法に別名を提供しました.
    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]])
    注意
    エイリアスメソッドを使用すると、  method 和  data 属性はconfigパラメータで指定する必要はありません.
    併発する
    併発要求を処理するヘルプ方法
    axios.all(iterable)
    axios.spread(calback)
    インスタンスを作成
    カスタム設定で新しいaxiosの例を作成できます.
    axios.reat([config])
    var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: { 'X-Custom-Header': 'foobar'} }); 
    実例的な方法
    利用可能なすべての例示的な方法は、以下に並べられています.指定された構成は、その例の構成と統合されます.
    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]])
    要求の設定
    以下は利用可能な要求設定項目です.  method ,デフォルトの要求方法は  { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', and 'PATCH' // The last function in the array must return a string or an ArrayBuffer transformRequest: [function (data) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: { 'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash data: { firstName: 'Fred' }, // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)). adapter: function (resolve, reject, config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' } // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text' responseType: 'json', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `progress` allows handling of progress events for 'POST' and 'PUT uploads' // as well as 'GET' downloads progress: function(progressEvent) { // Do whatever you want with the native progress event } } のデータ
    するデータは、 の を む.
    
        catch  ,
              :
     
    axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); 

    に してデフォルトの を できます.
    グローバルaxiosデフォルトの
    axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
    カスタムインスタンスのデフォルト
    // Set config defaults when creating the instance
    var instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 

    Config will be merged with an order of precedence.The order is library defaults found in  defaults property of the instance,and finally  config argment for the request.The latter will Tale precedence over the former.Here's an example.
    // Create an instance using the config defaults provided by the library
    // At this point the timeout config value is `0` as is the default for the library
    var instance = axios.create(); // Override timeout default for the library // Now all requests will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); 

    あなたが してもいいです  catch  ブロック と
    //          
    axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); //           axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); }); 
    ブロックを :
    var myInterceptor = axios.interceptors.request.use(function () { /*...*/}); axios.interceptors.request.eject(myInterceptor); 
    カスタマイズしたaxiosのインスタンスにブロックを できます.
    var instance = axios.create(); instance.interceptors.request.use(function () { /*...*/}); 
    エラー
    axios.get('/user/12345') .catch(function (response) { if (response instanceof Error) { // Something happened in setting up the request that triggered an Error console.log('Error', response.message); } else { // The request was made, but the server responded with a status code // that falls out of the range of 2xx console.log(response.data); console.log(response.status); console.log(response.headers); console.log(response.config); } }); 
    Promises
    axiosは のES 6 Promiseに しています.もしあなたのブラウザ がES 6 Promisesをサポートしていないなら、 してください. polyfill
    Type Script
    axiosは つを みます Type Script 

    Credits

    axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone  License MIT :https://www.awesomes.cn/repo/mzabriskie/axios

    :https://www.cnblogs.com/pangguoming/p/8435138.html