<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                [TOC] # OPTIONS 請求方法 HTTP 的?`OPTIONS 方法`?用于獲取目的資源所支持的通信選項。 以下三種情況瀏覽器會在發送正式請求先自動發送一個 OPTIONS 請求: - 跨域請求,非跨域請求不會出現 options 請求 - 請求設置了自定義的 header 字段 - 請求頭中的 Content-Type 是 application/x-www-form-urlencoded ,multipart/form-data,text/plain 之外的格式 在 CORS ?中,可以使用 OPTIONS 方法發起一個預檢請求,以檢測實際請求是否可以被服務器所接受。預檢請求報文中的?`Access-Control-Request-Method` 首部字段告知服務器實際請求所使用的 HTTP 方法;`Access-Control-Request-Headers` 首部字段告知服務器實際請求所攜帶的自定義首部字段。服務器基于從預檢請求獲得的信息來判斷,是否接受接下來的實際請求。 ```html OPTIONS /resources/post-here/ HTTP/1.1 Host: bar.other Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Origin: http://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type ``` 服務器所返回的`Access-Control-Allow-Methods`首部字段將所有允許的請求方法告知客戶端。 ```html HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 0 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain ``` # XMLHttpRequest | XMLHttpRequest對象方法 | 描述 | | --- | --- | | xhr.open('get', 'example.php', false) | 啟動一個請求以備發送,第三個參數為false表示異步,true表示同步發送 | | xhr.send(String) | 發送一個請求,接受一個可選的參數,其作為請求主體;如果請求方法是 GET 或者 HEAD,則應將請求主體設置為 null。 | | xhr.onreadystatechange= function () {} | 只要readyState屬性的值由一個值變為另一個值,都會觸發一次readystatechange事件 | | xhr.setRequestHeader('MyHeader', 'MyValue') | 用于設置自定義的請求頭部信息,必須在調用open方法之后和send方法之前調用 | | XMLHttpRequest對象屬性 | 描述 | | --- | --- | | xhr.status | 響應的HTTP狀態 | | xhr.statusText | HTTP狀態的說明 | | xhr.responseXML | 如果響應的內容類型是"text/html"或"application/xml",這個屬性將保存包含著響應數據的XML DOM文檔 | | xhr.readyState | 0:未初始化<br>1:啟動。已經調用open()方法,但尚未調用send()方法<br>2:發送。已經調用send()方法,但尚未接收到相應。<br>3:接收。已經收到部分響應數據。<br>4:完成:已經收到全部響應數據,而且已經可以在客戶端使用了 | | 進度事件 | 描述 | | --- | --- | | loadstart | 在接收到相應數據的第一個字節時觸發 | | progress| 在接收響應期間持續不斷地觸發 | | error | 在請求發生錯誤時觸發 | | abort| 在因調用abort()方法而終止連接時觸發 | | load| 在接收到完整的響應數據時觸發 | | loadend | 在通信完成或者觸發error、abort或load事件后觸發 | onprogress事件回調方法在`readyState==3`狀態時開始觸發, 默認傳入 ProgressEvent 對象, 可通過`e.loaded/e.total`來計算加載資源的進度, 該方法用于獲取資源的下載進度. ``` javaScript xhr.onprogress = function(e){ console.log('progress:', e.loaded/e.total); } ``` 更完整的整理:[AJAX 知識體系大梳理](http://louiszhai.github.io/2016/11/02/ajax/#%E4%BD%BF%E7%94%A8%E5%91%BD%E4%BB%A4%E6%B5%8B%E8%AF%95OPTIONS%E8%AF%B7%E6%B1%82) # axios庫的使用 安裝:`npm install aoxis` 導入:`import axios from axios` ## 請求發送的格式 1.`axios(config)`:通過向axios傳遞相關配置來創建請求 ```js // 發送 POST 請求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` 2.`axios(url[, config])` ```js // 發送 GET 請求(默認的方法) axios('/user/12345'); ``` ## 請求方法的別名 為方便起見,為所有支持的請求方法提供了別名 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\]\]) 在使用別名方法時,`url`、`method`、`data`這些屬性都不必在配置中指定。 1.只傳入一個參數,參數寫在URL中 ```js // 為給定 ID 的 user 創建請求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 2.第一個參數為 URL,第二個參數為配置選項;`params`是與請求一起發送的 URL 參數,`data`是作為請求主體被發送的數據,還有其他很多配置項。 ```js // 可選地,上面的請求可以這樣做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 3.可以自定義新建一個axios的實例,`axios.create(config)` ```js 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\]\]) ## 請求配置與響應結構 ``` { // `url` 是用于請求的服務器 URL url: '/user', // `method` 是創建請求時使用的方法 method: 'get', // 默認是 get // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允許在向服務器發送前,修改請求數據 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被發送的自定義請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一起發送的 URL 參數 // 必須是一個無格式對象(plain object)或 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` 是作為請求主體被發送的數據 // 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設置 `transformRequest` 時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'Fred' }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // 默認的 // `adapter` 允許自定義處理請求,以使測試更輕松 // 返回一個 promise 并應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,并提供憑據 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默認的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的 // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對于給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // 默認的 }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 如果設置為0,將不會 follow 任何重定向 maxRedirects: 5, // 默認的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用于定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項: // `keepAlive` 默認沒有啟用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義代理服務器的主機名稱和端口 // `auth` 表示 HTTP 基礎驗證應當用于連接代理,并提供憑據 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用于取消請求的 cancel token // (查看后面的 Cancellation 這節了解更多) cancelToken: new CancelToken(function (cancel) { }) } ``` 響應結構:某個請求的響應包含如下信息 ```js { data: {}, // `data` 由服務器提供的響應 status: 200, // `status` 來自服務器響應的 HTTP 狀態碼 statusText: 'OK', // `statusText` 來自服務器響應的 HTTP 狀態信息 headers: {}, // `headers` 服務器響應的頭 config: {} // `config` 是為請求提供的配置信息 } ``` ## 攔截器 在請求或響應被`then`或`catch`處理前攔截它們。 ```js // 添加請求攔截器 axios.interceptors.request.use(function (config) { // 在發送請求之前做些什么 return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); }); // 添加響應攔截器 axios.interceptors.response.use(function (response) { // 對響應數據做點什么 return response; }, function (error) { // 對響應錯誤做點什么 return Promise.reject(error); }); ``` 如果你想在稍后移除攔截器,可以這樣: ```js var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` 可以為自定義 axios 實例添加攔截器 ```js var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` # fetch API 參考: [https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch\_API/Using\_Fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch) [http://louiszhai.github.io/2016/11/02/fetch/](http://louiszhai.github.io/2016/11/02/fetch/) Fetch API 提供了一個全局`fetch()`方法,該方法提供了一種簡單,合理的方式來跨網絡異步獲取資源。 這種功能以前是使用 ?`XMLHttpRequest` 實現的,使用 XMLHttpRequest (XHR) 對象可以與服務器交互。您可以從 URL 獲取數據,而無需讓整個的頁面刷新。這使得 Web 頁面可以只更新頁面的局部,而不影響用戶的操作。 XMLHttpRequest 在?Ajax?編程中被大量使用。Fetch 提供了一個更好的替代方法,可以很容易地被其他技術使用,例如`Service Workers`。Fetch 還提供了單個邏輯位置來定義其他 HTTP 相關概念,例如 CORS 和 HTTP 的擴展。 請注意,`fetch`規范與`jQuery.ajax()`主要有兩種方式的不同,牢記: * 當接收到一個代表錯誤的 HTTP 狀態碼時,從?`fetch()`返回的 Promise **不會被標記為 reject,**?即使該 HTTP 響應的狀態碼是 404 或 500。相反,它會將 Promise 狀態標記為 resolve (但是會將 resolve 的返回值的`ok`屬性設置為 false ),僅當網絡故障時或請求被阻止時,才會標記為 reject。 * 默認情況下,`fetch`**不會從服務端發送或接收任何?cookies**, 如果站點依賴于用戶 session,則會導致未經認證的請求(要發送 cookies,必須設置 credentials 選項)。 一個基本的 fetch 請求設置起來很簡單。看看下面的代碼: ```js fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); }); ``` 這里我們通過網絡獲取一個 JSON 文件并將其打印到控制臺。最簡單的用法是只提供一個參數用來指明想`fetch()`到的資源路徑,然后返回一個包含響應結果的 promise 對象。使用 Response 對象的 json() 方法可以獲取 JSON 的內容 `fetch()`接受第二個可選參數,一個可以控制不同配置的?`init`?對象: ```js // Example POST method implementation: postData('http://example.com/answer', {answer: 42}) .then(data => console.log(data)) // JSON from `response.json()` call .catch(error => console.error(error)) function postData(url, data) { // Default options are marked with * return fetch(url, { body: JSON.stringify(data), // must match 'Content-Type' header cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(response => response.json()) // parses response to JSON } ``` ## 實踐 <span style="font-family:華文楷體;font-size: 18px; font-weight: 600;">上傳 JSON 數據</span> ```js var url = 'https://example.com/profile'; var data = {username: 'example'}; fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data), // data can be `string` or {object}! headers: new Headers({ 'Content-Type': 'application/json' }) }).then(res => res.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response)); ``` <span style="font-family:華文楷體;font-size: 18px; font-weight: 600;">上傳文件</span> ```js var formData = new FormData(); var fileField = document.querySelector("input[type='file']"); formData.append('username', 'abc123'); formData.append('avatar', fileField.files[0]); fetch('https://example.com/profile/avatar', { method: 'PUT', body: formData }) .then(response => response.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response)); ``` <span style="font-family:華文楷體;font-size: 18px; font-weight: 600;">fetch 的缺點</span> fetch 是比較底層的 API,雖然其用起來較為簡單,但是仍然存在一些缺點: - 只對網絡請求報錯,對 400,500 都當作成功的請求。 - 默認不會帶 cookie - 不支持 abort,不支持超時控制 - 無法原生監測請求的進度
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看