中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

網(wǎng)站模版調(diào)用標(biāo)簽教程站長檢測工具

網(wǎng)站模版調(diào)用標(biāo)簽教程,站長檢測工具,微信自動加好友軟件,seo1網(wǎng)站查詢1、Axios介紹 Axios基于promise網(wǎng)絡(luò)請求庫,作用于node.js和瀏覽器中(即同一套代碼可以運行在node.js和瀏覽器中),在服務(wù)器中他使用原生node.js http,在瀏覽器端則使用XMLHttpRequest。 特性: (1)、支持 Pro…

1、Axios介紹
Axios基于promise網(wǎng)絡(luò)請求庫,作用于node.js和瀏覽器中(即同一套代碼可以運行在node.js和瀏覽器中),在服務(wù)器中他使用原生node.js http,在瀏覽器端則使用XMLHttpRequest。
特性:
(1)、支持 Promise API
(2)、攔截請求和響應(yīng)、轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)、取消請求
(3)、自動轉(zhuǎn)換JSON數(shù)據(jù)、客戶端支持防御XSRF
安裝:
(1)、使用npm
npm install axios
(2)、使用yarn
yarn add axios

2、基本用例
CommonJS用法:

const axios = require('axios').default;

// axios. 能夠提供自動完成和參數(shù)類型推斷功能
(1)、get請求
寫法1:

axios.get('/user?ID=12345')

寫法2:

axios.get('/user', {params: {ID: 12345}})const axios = require('axios');// 向給定ID的用戶發(fā)起請求
axios.get('/user?ID=12345').then(function (response) {// 處理成功情況console.log(response);}).catch(function (error) {// 處理錯誤情況console.log(error);}).then(function () {// 總是會執(zhí)行});// 支持async/await用法
async function getUser() {try {const response = await axios.get('/user?ID=12345');console.log(response);} catch (error) {console.error(error);}
}

發(fā)起多個并發(fā)請求

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];});

(2)、Post請求

axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});

(3)、Axios API
axios(config)
可以向 axios 傳遞相關(guān)配置來創(chuàng)建請求

// 發(fā)起一個post請求
axios({method: 'post',url: '/user/12345',data: {firstName: 'Fred',lastName: 'Flintstone'}
});

// 在 node.js 用GET請求獲取遠(yuǎn)程圖片

axios({method: 'get',url: 'http://bit.ly/2mTM3nY',responseType: 'stream'
}).then(function (response) {response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});
axios(url[, config])

// 發(fā)起一個 GET 請求 (默認(rèn)請求方式)

axios('/user/12345');

請求方式別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注意
在使用別名方法時, url、method、data 這些屬性都不必在配置中指定。

3、Axios 實例
創(chuàng)建一個實例

axios.create([config])
const 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#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

4、請求配置
這些是創(chuàng)建請求時可以用的配置選項。只有 url 是必需的。如果沒有指定 method,請求將默認(rèn)使用 GET 方法。

{// `url` 是用于請求的服務(wù)器 URLurl: '/user',// `method` 是創(chuàng)建請求時使用的方法method: 'get', // 默認(rèn)值// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。// 它可以通過設(shè)置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URLbaseURL: 'https://some-domain.com/api/',// `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請求數(shù)據(jù)// 它只能用于 'PUT', 'POST' 和 'PATCH' 這幾個請求方法// 數(shù)組中最后一個函數(shù)必須返回一個字符串, 一個Buffer實例,ArrayBuffer,FormData,或 Stream// 你可以修改請求頭。transformRequest: [function (data, headers) {// 對發(fā)送的 data 進行任意轉(zhuǎn)換處理return data;}],// `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)transformResponse: [function (data) {// 對接收的 data 進行任意轉(zhuǎn)換處理return data;}],// 自定義請求頭headers: {'X-Requested-With': 'XMLHttpRequest'},// `params` 是與請求一起發(fā)送的 URL 參數(shù)// 必須是一個簡單對象或 URLSearchParams 對象params: {ID: 12345},// `paramsSerializer`是可選方法,主要用于序列化`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` 是作為請求體被發(fā)送的數(shù)據(jù)// 僅適用 'PUT', 'POST', 'DELETE 和 'PATCH' 請求方法// 在沒有設(shè)置 `transformRequest` 時,則必須是以下類型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 瀏覽器專屬: FormData, File, Blob// - Node 專屬: Stream, Bufferdata: {firstName: 'Fred'},// 發(fā)送請求體數(shù)據(jù)的可選語法// 請求方式 post// 只有 value 會被發(fā)送,key 則不會data: 'Country=Brasil&City=Belo Horizonte',// `timeout` 指定請求超時的毫秒數(shù)。// 如果請求時間超過 `timeout` 的值,則請求會被中斷timeout: 1000, // 默認(rèn)值是 `0` (永不超時)// `withCredentials` 表示跨域請求時是否需要使用憑證withCredentials: false, // default// `adapter` 允許自定義處理請求,這使測試更加容易。// 返回一個 promise 并提供一個有效的響應(yīng) (參見 lib/adapters/README.md)。adapter: function (config) {/* ... */},// `auth` HTTP Basic Authauth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` 表示瀏覽器將要響應(yīng)的數(shù)據(jù)類型// 選項包括: 'arraybuffer', 'document', 'json', 'text', 'stream'// 瀏覽器專屬:'blob'responseType: 'json', // 默認(rèn)值// `responseEncoding` 表示用于解碼響應(yīng)的編碼 (Node.js 專屬)// 注意:忽略 `responseType` 的值為 'stream',或者是客戶端請求// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: 'utf8', // 默認(rèn)值// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名稱xsrfCookieName: 'XSRF-TOKEN', // 默認(rèn)值// `xsrfHeaderName` 是帶有 xsrf token 值的http 請求頭名稱xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)值// `onUploadProgress` 允許為上傳處理進度事件// 瀏覽器專屬onUploadProgress: function (progressEvent) {// 處理原生進度事件},// `onDownloadProgress` 允許為下載處理進度事件// 瀏覽器專屬onDownloadProgress: function (progressEvent) {// 處理原生進度事件},// `maxContentLength` 定義了node.js中允許的HTTP響應(yīng)內(nèi)容的最大字節(jié)數(shù)maxContentLength: 2000,// `maxBodyLength`(僅Node)定義允許的http請求內(nèi)容的最大字節(jié)數(shù)maxBodyLength: 2000,// `validateStatus` 定義了對于給定的 HTTP狀態(tài)碼是 resolve 還是 reject promise。// 如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),// 則promise 將會 resolved,否則是 rejected。validateStatus: function (status) {return status >= 200 && status < 300; // 默認(rèn)值},// `maxRedirects` 定義了在node.js中要遵循的最大重定向數(shù)。// 如果設(shè)置為0,則不會進行重定向maxRedirects: 5, // 默認(rèn)值// `socketPath` 定義了在node.js中使用的UNIX套接字。// e.g. '/var/run/docker.sock' 發(fā)送請求到 docker 守護進程。// 只能指定 `socketPath` 或 `proxy` 。// 若都指定,這使用 `socketPath` 。socketPath: null, // default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// `proxy` 定義了代理服務(wù)器的主機名,端口和協(xié)議。// 您可以使用常規(guī)的`http_proxy` 和 `https_proxy` 環(huán)境變量。// 使用 `false` 可以禁用代理功能,同時環(huán)境變量也會被忽略。// `auth`表示應(yīng)使用HTTP Basic auth連接到代理,并且提供憑據(jù)。// 這將設(shè)置一個 `Proxy-Authorization` 請求頭,它會覆蓋 `headers` 中已存在的自定義 `Proxy-Authorization` 請求頭。// 如果代理服務(wù)器使用 HTTPS,則必須設(shè)置 protocol 為`https`proxy: {protocol: 'https',host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// see https://axios-http.com/zh/docs/cancellationcancelToken: new CancelToken(function (cancel) {}),// `decompress` indicates whether or not the response body should be decompressed // automatically. If set to `true` will also remove the 'content-encoding' header // from the responses objects of all decompressed responses// - Node only (XHR cannot turn off decompression)decompress: true // 默認(rèn)值
}

5、響應(yīng)結(jié)構(gòu)
一個請求的響應(yīng)包含以下信息。

{// `data` 由服務(wù)器提供的響應(yīng)data: {},// `status` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼status: 200,// `statusText` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息statusText: 'OK',// `headers` 是服務(wù)器響應(yīng)頭// 所有的 header 名稱都是小寫,而且可以使用方括號語法訪問// 例如: `response.headers['content-type']`headers: {},// `config` 是 `axios` 請求的配置信息config: {},// `request` 是生成此響應(yīng)的請求// 在node.js中它是最后一個ClientRequest實例 (in redirects),// 在瀏覽器中則是 XMLHttpRequest 實例request: {}
}

6、默認(rèn)配置
您可以指定默認(rèn)配置,它將作用于每個請求。

全局 axios 默認(rèn)值

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';

自定義實例默認(rèn)值
// 創(chuàng)建實例時配置默認(rèn)值

const instance = axios.create({baseURL: 'https://api.example.com'
});

// 創(chuàng)建實例后修改默認(rèn)值

instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的優(yōu)先級
配置將會按優(yōu)先級進行合并。它的順序是:在lib/defaults.js中找到的庫默認(rèn)值,然后是實例的 defaults 屬性,最后是請求的 config 參數(shù)。后面的優(yōu)先級要高于前面的。下面有一個例子。

// 使用庫提供的默認(rèn)配置創(chuàng)建實例
// 此時超時配置的默認(rèn)值是 0

const instance = axios.create();

// 重寫庫的超時默認(rèn)值
// 現(xiàn)在,所有使用此實例的請求都將等待2.5秒,然后才會超時

instance.defaults.timeout = 2500;

// 重寫此請求的超時時間,因為該請求需要很長時間

instance.get('/longRequest', {timeout: 5000
});

7、攔截器
在請求或響應(yīng)被 then 或 catch 處理前攔截它們。

// 添加請求攔截器
axios.interceptors.request.use(function (config) {// 在發(fā)送請求之前做些什么return config;}, function (error) {// 對請求錯誤做些什么return Promise.reject(error);});// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {// 2xx 范圍內(nèi)的狀態(tài)碼都會觸發(fā)該函數(shù)。// 對響應(yīng)數(shù)據(jù)做點什么return response;}, function (error) {// 超出 2xx 范圍的狀態(tài)碼都會觸發(fā)該函數(shù)。// 對響應(yīng)錯誤做點什么return Promise.reject(error);});

如果你稍后需要移除攔截器,可以這樣:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

可以給自定義的 axios 實例添加攔截器。

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

8、錯誤處理

axios.get('/user/12345').catch(function (error) {if (error.response) {// 請求成功發(fā)出且服務(wù)器也響應(yīng)了狀態(tài)碼,但狀態(tài)代碼超出了 2xx 的范圍console.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {// 請求已經(jīng)成功發(fā)起,但沒有收到響應(yīng)// `error.request` 在瀏覽器中是 XMLHttpRequest 的實例,// 而在node.js中是 http.ClientRequest 的實例console.log(error.request);} else {// 發(fā)送請求時出了點問題console.log('Error', error.message);}console.log(error.config);});

使用 validateStatus 配置選項,可以自定義拋出錯誤的 HTTP code。

axios.get('/user/12345', {validateStatus: function (status) {return status < 500; // 處理狀態(tài)碼小于500的情況}
})

使用 toJSON 可以獲取更多關(guān)于HTTP錯誤的信息。

axios.get('/user/12345').catch(function (error) {console.log(error.toJSON());});

9、取消請求
AbortController
從 v0.22.0 開始,Axios 支持以 fetch API 方式—— AbortController 取消請求:

const controller = new AbortController();axios.get('/foo/bar', {signal: controller.signal
}).then(function(response) {//...
});
// 取消請求
controller.abort()
CancelToken deprecated

您還可以使用 cancel token 取消一個請求。

Axios 的 cancel token API 是基于被撤銷 cancelable promises proposal。

此 API 從 v0.22.0 開始已被棄用,不應(yīng)在新項目中使用。

可以使用 CancelToken.source 工廠方法創(chuàng)建一個 cancel token ,如下所示:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();axios.get('/user/12345', {cancelToken: source.token
}).catch(function (thrown) {if (axios.isCancel(thrown)) {console.log('Request canceled', thrown.message);} else {// 處理錯誤}
});axios.post('/user/12345', {name: 'new name'
}, {cancelToken: source.token
})// 取消請求(message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.');

也可以通過傳遞一個 executor 函數(shù)到 CancelToken 的構(gòu)造函數(shù)來創(chuàng)建一個 cancel token:

const CancelToken = axios.CancelToken;
let cancel;axios.get('/user/12345', {cancelToken: new CancelToken(function executor(c) {// executor 函數(shù)接收一個 cancel 函數(shù)作為參數(shù)cancel = c;})
});// 取消請求
cancel();

注意: 可以使用同一個 cancel token 或 signal 取消多個請求。

在過渡期間,您可以使用這兩種取消 API,即使是針對同一個請求:

const controller = new AbortController();const CancelToken = axios.CancelToken;
const source = CancelToken.source();axios.get('/user/12345', {cancelToken: source.token,signal: controller.signal
}).catch(function (thrown) {if (axios.isCancel(thrown)) {console.log('Request canceled', thrown.message);} else {// 處理錯誤}
});axios.post('/user/12345', {name: 'new name'
}, {cancelToken: source.token
})// 取消請求 (message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.');
// 或
controller.abort(); // 不支持 message 參數(shù)

10、請求體編碼
默認(rèn)情況下,axios將 JavaScript 對象序列化為 JSON 。 要以application/x-www-form-urlencoded格式發(fā)送數(shù)據(jù),您可以使用以下選項之一。

瀏覽器
在瀏覽器中,可以使用URLSearchParams API,如下所示:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

請注意,不是所有的瀏覽器(參見 caniuse.com)都支持 URLSearchParams ,但是可以使用polyfill (確保 polyfill 全局環(huán)境)

或者, 您可以使用qs 庫編碼數(shù)據(jù):

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

或者用另一種方式 (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {method: 'POST',headers: { 'content-type': 'application/x-www-form-urlencoded' },data: qs.stringify(data),url,
};
axios(options);

Node.js
Query string
在 node.js 中, 可以使用 querystring 模塊,如下所示:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

或者從’url module’中使用’URLSearchParams’,如下所示:

const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());

您也可以使用 qs 庫。

注意
如果需要對嵌套對象進行字符串化處理,則最好使用 qs 庫,因為 querystring 方法在該用例中存在已知問題(https://github.com/nodejs/node-v0.x-archive/issues/1665)。

Form data
在 node.js, 您可以使用 form-data 庫,如下所示:

const FormData = require('form-data');const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));axios.post('https://example.com', form, { headers: form.getHeaders() })

或者, 使用一個攔截器:

axios.interceptors.request.use(config => {if (config.data instanceof FormData) {Object.assign(config.headers, config.data.getHeaders());}return config;
});

11、注意事項
語義化
在axios達到 1.0 版本之前,破壞性更改將以新的次要版本發(fā)布。 例如 0.5.1 和 0.5.4 將具有相同的 API,但 0.6.0 將具有重大變化。

Promises
axios 依賴原生的ES6 Promise實現(xiàn)而被支持。 如果你的環(huán)境不支持 ES6 Promise,你可以使用polyfill。

TypeScript
axios 包含 TypeScript 類型定義。

import axios from 'axios';
axios.get('/user?ID=12345');
http://www.risenshineclean.com/news/51884.html

相關(guān)文章:

  • Wordpress怎么上傳html文件泰州網(wǎng)站優(yōu)化公司
  • 知名的政府網(wǎng)站建設(shè)企業(yè)鏈接點擊量軟件
  • 網(wǎng)站建設(shè)公司 廣告法被處罰營銷客戶管理系統(tǒng)
  • wordpress網(wǎng)站正在維護中網(wǎng)站模板平臺資源
  • 網(wǎng)頁模板怎么做網(wǎng)站關(guān)鍵詞優(yōu)化多少錢
  • 龍巖龍硿洞在線優(yōu)化seo
  • 建設(shè)網(wǎng)站實驗活動小結(jié)百度快速排名優(yōu)化工具
  • 政府網(wǎng)站欄目架構(gòu)大學(xué)生網(wǎng)頁設(shè)計主題
  • 網(wǎng)站建設(shè)推廣頁農(nóng)業(yè)推廣
  • 如何維護網(wǎng)站百度seo排名優(yōu)化軟件化
  • 做優(yōu)化的網(wǎng)站電話軟文推廣一般發(fā)布在哪些平臺
  • wordpress 安全 插件重慶seo公司排名
  • 網(wǎng)站建設(shè) 有聊天工具的嗎百度一下你知道
  • seo需要會網(wǎng)站建設(shè)嗎web個人網(wǎng)站設(shè)計代碼
  • wordpress get locale邵陽網(wǎng)站seo
  • 偃師制作網(wǎng)站怎么去營銷自己的產(chǎn)品
  • 江蘇緣生源建設(shè)工程有限公司網(wǎng)站游戲推廣拉人渠道
  • 南京建設(shè)銀行網(wǎng)站首頁想要推廣頁
  • 高仿微博wordpressseo狂人
  • 湖南專業(yè)做網(wǎng)站公司怎樣推廣app
  • 上海如何優(yōu)化網(wǎng)站新河seo怎么做整站排名
  • 做汽車團購的網(wǎng)站建設(shè)北京seo代理公司
  • 電子商務(wù)b2c網(wǎng)站建設(shè)選擇寧波seo優(yōu)化公司
  • 高校學(xué)生紅色網(wǎng)站建設(shè)電子商務(wù)專業(yè)就業(yè)方向
  • 福建建設(shè)科技人才網(wǎng)站網(wǎng)絡(luò)銷售怎么干
  • 網(wǎng)站建設(shè)續(xù)費合同近日網(wǎng)站收錄查詢
  • 網(wǎng)站 網(wǎng)頁設(shè)計網(wǎng)站制作公司有哪些
  • 加強網(wǎng)站政務(wù)服務(wù)建設(shè)方案seo網(wǎng)站關(guān)鍵詞排名快速
  • 網(wǎng)站制作html代碼簡述網(wǎng)站制作的步驟
  • 在線做網(wǎng)站 自動生成手機版seo的定義是什么