偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Axios 是如何封裝 HTTP 請求的

開發(fā) 前端
本文用來整理項目中常用的 Axios 的封裝使用。同時學(xué)習(xí)源碼,手寫實現(xiàn) Axios 的核心代碼。

Axios 毋庸多說大家在前端開發(fā)中常用的一個發(fā)送 HTTP 請求的庫,用過的都知道。本文用來整理項目中常用的 Axios 的封裝使用。同時學(xué)習(xí)源碼,手寫實現(xiàn) Axios 的核心代碼。

Axios 常用封裝

是什么

Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。它的特性:

  •  從瀏覽器中創(chuàng)建 XMLHttpRequests
  •  從 node.js 創(chuàng)建 http 請求
  •  支持 Promise API
  •  攔截請求和響應(yīng)
  •  轉(zhuǎn)換請求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  •  取消請求
  •  自動轉(zhuǎn)換 JSON 數(shù)據(jù)
  •  客戶端支持防御 XSRF官網(wǎng)地址:http://www.axios-js.com/zh-cn/docs/#axios-config

Axios 使用方式有兩種:一種是直接使用全局的 Axios 對象;另外一種是通過 axios.create(config) 方法創(chuàng)建一個實例對象,使用該對象。兩種方式的區(qū)別是通過第二種方式創(chuàng)建的實例對象更清爽一些;全局的 Axios 對象其實也是創(chuàng)建的實例對象導(dǎo)出的,它本身上加載了很多默認(rèn)屬性。后面源碼學(xué)習(xí)的時候會再詳細(xì)說明。

請求

Axios 這個 HTTP 的庫比較靈活,給用戶多種發(fā)送請求的方式,以至于有些混亂。細(xì)心整理會發(fā)現(xiàn),全局的 Axios(或者 axios.create(config)創(chuàng)建的對象) 既可以當(dāng)作對象使用,也可以當(dāng)作函數(shù)使用: 

  1. // axios 當(dāng)作對象使用  
  2. axios.request(config)  
  3. axios.get(url[, config])  
  4. axios.post(url[, data[, config]])  
  1. // axios() 當(dāng)作函數(shù)使用。 發(fā)送 POST 請求  
  2. axios({  
  3.   method: 'post',  
  4.   url: '/user/12345',  
  5.   data: {  
  6.     firstName: 'Fred',  
  7.     lastName: 'Flintstone'  
  8.   }  
  9. }); 

后面源碼學(xué)習(xí)的時候會再詳細(xì)說明為什么 Axios 可以實現(xiàn)兩種方式的使用。

取消請求

可以使用 CancelToken.source 工廠方法創(chuàng)建 cancel token: 

  1. const CancelToken = axios.CancelToken;  
  2. const source = CancelToken.source();  
  3. axios.get('/user/12345', {  
  4.   cancelToken: source.token  
  5. }).catch(function(thrown) {  
  6.   if (axios.isCancel(thrown)) {  
  7.     console.log('Request canceled', thrown.message);  
  8.   } else { 
  9.       // 處理錯誤  
  10.   }  
  11. });  
  12. // 取消請求(message 參數(shù)是可選的)  
  13. source.cancel('Operation canceled by the user.'); 

source 有兩個屬性:一個是 source.token 標(biāo)識請求;另一個是 source.cancel() 方法,該方法調(diào)用后,可以讓 CancelToken 實例的 promise 狀態(tài)變?yōu)?resolved,從而觸發(fā) xhr 對象的 abort() 方法,取消請求。

攔截

Axios 還有一個奇妙的功能點,可以在發(fā)送請求前對請求進(jìn)行攔截,對相應(yīng)結(jié)果進(jìn)行攔截。結(jié)合業(yè)務(wù)場景的話,在中臺系統(tǒng)中完成登錄后,獲取到后端返回的 token,可以將 token 添加到 header 中,以后所有的請求自然都會加上這個自定義 header。 

  1. //攔截1 請求攔截  
  2. instance.interceptors.request.use(function(config){  
  3.     //在發(fā)送請求之前做些什么  
  4.     const token = sessionStorage.getItem('token');  
  5.     if(token){  
  6.         const newConfig = {  
  7.             ...config,  
  8.             headers: {  
  9.                 token: token  
  10.             }  
  11.         }  
  12.         return newConfig;  
  13.     }else{  
  14.         return config;  
  15.     }  
  16. }, function(error){  
  17.     //對請求錯誤做些什么  
  18.     return Promise.reject(error);  
  19. }); 

我們還可以利用請求攔截功能實現(xiàn) 取消重復(fù)請求,也就是在前一個請求還沒有返回之前,用戶重新發(fā)送了請求,需要先取消前一次請求,再發(fā)送新的請求。比如搜索框自動查詢,當(dāng)用戶修改了內(nèi)容重新發(fā)送請求的時候需要取消前一次請求,避免請求和響應(yīng)混亂。再比如表單提交按鈕,用戶多次點擊提交按鈕,那么我們就需要取消掉之前的請求,保證只有一次請求的發(fā)送和響應(yīng)。

實現(xiàn)原理是使用一個對象記錄已經(jīng)發(fā)出去的請求,在請求攔截函數(shù)中先判斷這個對象中是否記錄了本次請求信息,如果已經(jīng)存在,則取消之前的請求,將本次請求添加進(jìn)去對象中;如果沒有記錄過本次請求,則將本次請求信息添加進(jìn)對象中。最后請求完成后,在響應(yīng)攔截函數(shù)中執(zhí)行刪除本次請求信息的邏輯。 

  1. // 攔截2   重復(fù)請求,取消前一個請求  
  2. const promiseArr = {};  
  3. instance.interceptors.request.use(function(config){  
  4.     console.log(Object.keys(promiseArr).length)  
  5.     //在發(fā)送請求之前做些什么  
  6.     let source=null 
  7.     if(config.cancelToken){  
  8.         // config 配置中帶了 source 信息  
  9.         source = config.source;  
  10.     }else{  
  11.         const CancelToken = axios.CancelToken;  
  12.         source = CancelToken.source();  
  13.         config.cancelToken = source.token;  
  14.     }  
  15.     const currentKey = getRequestSymbol(config);  
  16.     if(promiseArr[currentKey]){  
  17.         const tmp = promiseArr[currentKey];  
  18.         tmp.cancel("取消前一個請求");  
  19.         delete promiseArr[currentKey];  
  20.         promiseArr[currentKey] = source;  
  21.     }else{  
  22.         promiseArr[currentKey] = source;  
  23.     }  
  24.     return config;  
  25. }, function(error){  
  26.     //對請求錯誤做些什么  
  27.     return Promise.reject(error);  
  28. });  
  29. // 根據(jù) url、method、params 生成唯一標(biāo)識,大家可以自定義自己的生成規(guī)則  
  30. function getRequestSymbol(config){  
  31.     const arr = [];  
  32.     if(config.params){  
  33.         const data = config.params;  
  34.         for(let key of Object.keys(data)){  
  35.             arr.push(key+"&"+data[key]);  
  36.         }  
  37.         arr.sort();  
  38.     }  
  39.     return config.url+config.method+arr.join("");  
  40.  
  41. instance.interceptors.response.use(function(response){  
  42.     const currentKey = getRequestSymbol(response.config);  
  43.     delete promiseArr[currentKey];  
  44.     return response;  
  45. }, function(error){  
  46.     //對請求錯誤做些什么  
  47.     return Promise.reject(error);  
  48. }); 

最后,我們可以在響應(yīng)攔截函數(shù)中統(tǒng)一處理返回碼的邏輯: 

  1. // 響應(yīng)攔截  
  2. instance.interceptors.response.use(function(response){  
  3.     // 401 沒有登錄跳轉(zhuǎn)到登錄頁面  
  4.     if(response.data.code===401){  
  5.         window.location.href = "http://127.0.0.1:8080/#/login" 
  6.     }else if(response.data.code===403){  
  7.         // 403 無權(quán)限跳轉(zhuǎn)到無權(quán)限頁面  
  8.         window.location.href = "http://127.0.0.1:8080/#/noAuth" 
  9.     }  
  10.     return response;  
  11. }, function(error){  
  12.     //對請求錯誤做些什么  
  13.     return Promise.reject(error);  
  14. }) 

文件下載

通常文件下載有兩種方式:一種是通過文件在服務(wù)器上的對外地址直接下載;還有一種是通過接口將文件以二進(jìn)制流的形式下載。

第一種:同域名 下使用 a 標(biāo)簽下載: 

  1. // httpServer.js  
  2. const express = require("express");  
  3. const path = require('path');  
  4. const app = express();  
  5. //靜態(tài)文件地址  
  6. app.use(express.static(path.join(__dirname, 'public')))  
  7. app.use(express.static(path.join(__dirname, '../')));  
  8. app.listen(8081, () => {  
  9.   console.log("服務(wù)器啟動成功!")  
  10. });  
  1. // index.html  
  2. <a href="test.txt" download="test.txt">下載</a> 

第二種:二進(jìn)制文件流的形式傳遞,我們直接訪問該接口并不能下載文件,一定程度保證了數(shù)據(jù)的安全性。比較多的場景是:后端接收到查詢參數(shù),查詢數(shù)據(jù)庫然后通過插件動態(tài)生成 excel 文件,以文件流的方式讓前端下載。

這時候,我們可以將請求文件下載的邏輯進(jìn)行封裝。將二進(jìn)制文件流存在 Blob 對象中,再將其轉(zhuǎn)為 url 對象,最后通過 a 標(biāo)簽下載。 

  1. //封裝下載  
  2. export function downLoadFetch(url, params = {}, config={}) {  
  3.     //取消  
  4.     const downSource = axios.CancelToken.source();  
  5.     document.getElementById('downAnimate').style.display = 'block' 
  6.     document.getElementById('cancelBtn').addEventListener('click', function(){  
  7.         downSource.cancel("用戶取消下載");  
  8.         document.getElementById('downAnimate').style.display = 'none' 
  9.     }, false);  
  10.     //參數(shù)  
  11.     config.params = params;  
  12.     //超時時間  
  13.     configconfig.timeout = config.timeout ? config.timeout : defaultDownConfig.timeout;  
  14.     //類型  
  15.     config.responseType = defaultDownConfig.responseType;  
  16.     //取消下載  
  17.     config.cancelToken = downSource.token;  
  18.     return instance.get(url, config).then(response=> 
  19.         const content = response.data;  
  20.         const url = window.URL.createObjectURL(new Blob([content]));  
  21.         //創(chuàng)建 a 標(biāo)簽  
  22.         const link = document.createElement('a');  
  23.         link.style.display = 'none' 
  24.         link.href = url 
  25.         //文件名  Content-Disposition: attachment; filename=download.txt  
  26.         const filename = response.headers['content-disposition'].split(";")[1].split("=")[1];  
  27.         link.download = filename 
  28.         document.body.appendChild(link);  
  29.         link.click();  
  30.         document.body.removeChild(link);  
  31.         return {  
  32.             status: 200,  
  33.             success: true  
  34.         }  
  35.     })  

手寫 Axios 核心代碼

寫了這么多用法終于到正題了,手寫 Axios 核心代碼。Axios 這個庫源碼不難閱讀,沒有特別復(fù)雜的邏輯,大家可以放心閱讀 😂 。

源碼入口是這樣查找:在項目 node_modules 目錄下,找到 axios 模塊的 package.json 文件,其中 "main": "index.js", 就是文件入口。一步步我們可以看到源碼是怎么串起來的。

模仿上面的目錄結(jié)構(gòu),我們創(chuàng)建自己的目錄結(jié)構(gòu): 

  1. axios-js  
  2. │  index.html  
  3. │    
  4. └─lib  
  5.         adapter.js  
  6.         Axios.js  
  7.         axiosInstance.js  
  8.         CancelToken.js  
  9.         InterceptorManager.js 

Axios 是什么

上面有提到我們使用的全局 Axios 對象其實也是構(gòu)造出來的 axios,既可以當(dāng)對象使用調(diào)用 get、post 等方法,也可以直接當(dāng)作函數(shù)使用。這是因為全局的 Axios 其實是函數(shù)對象 instance 。源碼位置在 axios/lib/axios.js 中。具體代碼如下: 

  1. // axios/lib/axios.js  
  2. //創(chuàng)建 axios 實例  
  3. function createInstance(defaultConfig) {  
  4.   var context = new Axios(defaultConfig);  
  5.   //instance 對象是 bind 返回的函數(shù)  
  6.   var instance = bind(Axios.prototype.request, context);  
  7.   // Copy axios.prototype to instance  
  8.   utils.extend(instance, Axios.prototype, context);  
  9.   // Copy context to instance  
  10.   utils.extend(instance, context);  
  11.   return instance;  
  12.  
  13. // 實例一個 axios  
  14. var axios = createInstance(defaults);  
  15. // 向這個實例添加 Axios 屬性  
  16. axios.Axios = Axios;  
  17. // 向這個實例添加 create 方法  
  18. axios.create = function create(instanceConfig) {  
  19.   return createInstance(mergeConfig(axios.defaults, instanceConfig));  
  20. };  
  21. // 向這個實例添加 CancelToken 方法  
  22. axios.CancelToken = require('./cancel/CancelToken'); 
  23. // 導(dǎo)出實例 axios  
  24. module.exports.default = axios

根據(jù)上面的源碼,我們可以簡寫一下自己實現(xiàn) Axios.js 和 axiosInstance.js: 

  1. // Axios.js  
  2. //Axios 主體  
  3. function Axios(config){ 
  4.  
  5. // 核心方法,發(fā)送請求  
  6. Axios.prototype.request = function(config){  
  7.  
  8. Axios.prototype.get = function(url, config={}){  
  9.     return this.request({url: url, method: 'GET', ...config});  
  10.  
  11. Axios.prototype.post = function(url, data, config={}){  
  12.     return this.request({url: url, method: 'POST', data: data, ...config})  
  13.  
  14. export default Axios; 

在 axiosInstance.js 文件中,實例化一個 Axios 得到 context,再將原型對象上的方法綁定到 instance 對象上,同時將 context 的屬性添加到 instance 上。這樣 instance 就成為了一個函數(shù)對象。既可以當(dāng)作對象使用,也可以當(dāng)作函數(shù)使用。 

  1. // axiosInstance.js  
  2. //創(chuàng)建實例  
  3. function createInstance(config){  
  4.     const context = new Axios(config);  
  5.     var instance = Axios.prototype.request.bind(context);  
  6.     //將 Axios.prototype 屬性擴(kuò)展到 instance 上  
  7.     for(let k of Object.keys(Axios.prototype)){  
  8.         instance[k] = Axios.prototype[k].bind(context);  
  9.     }  
  10.     //將 context 屬性擴(kuò)展到 instance 上  
  11.     for(let k of Object.keys(context)){  
  12.         instance[k] = context[k]  
  13.     }  
  14.     return instance;  
  15.  
  16. const axios = createInstance({});  
  17. axios.create = function(config){  
  18.     return createInstance(config);  
  19.  export default axios; 

也就是說 axios.js 中導(dǎo)出的 axios 對象并不是 new Axios() 方法返回的對象 context,而是 Axios.prototype.request.bind(context) 執(zhí)行返回的 instance,通過遍歷 Axios.prototype 并改變其 this 指向到 context;遍歷 context 對象讓 instance 對象具有 context 的所有屬性。這樣 instance 對象就無敵了,😎 既擁有了 Axios.prototype 上的所有方法,又具有了 context 的所有屬性。

請求實現(xiàn)

我們知道 Axios 在瀏覽器中會創(chuàng)建 XMLHttpRequest 對象,在 node.js 環(huán)境中創(chuàng)建 http 發(fā)送請求。Axios.prototype.request() 是發(fā)送請求的核心方法,這個方法其實調(diào)用的是 dispatchRequest 方法,而 dispatchRequest 方法調(diào)用的是 config.adapter || defaults.adapter 也就是自定義的 adapter 或者默認(rèn)的 defaults.adapter,默認(rèn)defaults.adapter 調(diào)用的是 getDefaultAdapter 方法,源碼: 

  1. function getDefaultAdapter() {  
  2.   var adapter;  
  3.   if (typeof XMLHttpRequest !== 'undefined') {  
  4.     // For browsers use XHR adapter  
  5.     adapter = require('./adapters/xhr');  
  6.   } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {  
  7.     // For node use HTTP adapter  
  8.     adapter = require('./adapters/http');  
  9.   }  
  10.   return adapter;  

哈哈哈,getDefaultAdapter 方法最終根據(jù)當(dāng)前的環(huán)境返回不同的實現(xiàn)方法,這里用到了 適配器模式。我們只用實現(xiàn) xhr 發(fā)送請求即可: 

  1. //適配器 adapter.js  
  2. function getDefaultAdapter(){  
  3.     var adapter;  
  4.     if(typeof XMLHttpRequest !== 'undefined'){  
  5.         //導(dǎo)入 XHR 對象請求  
  6.         adapter = (config)=> 
  7.             return xhrAdapter(config);  
  8.         }  
  9.     }  
  10.     return adapter;  
  11.  
  12. function xhrAdapter(config){  
  13.     return new Promise((resolve, reject)=> 
  14.         var xhr = new XMLHttpRequest();  
  15.         xhr.open(config.method, config.url, true);  
  16.         xhr.send();  
  17.         xhr.onreadystatechange = ()=> 
  18.             if(xhr.readyState===4){  
  19.                 if(xhr.status>=200&&xhr.status<300){  
  20.                     resolve({  
  21.                         data: {},  
  22.                         status: xhr.status,  
  23.                         statusText: xhr.statusText,  
  24.                         xhr: xhr 
  25.                     })  
  26.                 }else{  
  27.                     reject({ 
  28.                          status: xhr.status  
  29.                     })  
  30.                 }  
  31.             }  
  32.         };  
  33.     })  
  34.  export default getDefaultAdapter; 

這樣就理順了,getDefaultAdapter 方法每次執(zhí)行會返回一個 Promise 對象,這樣 Axios.prototype.request 方法可以得到執(zhí)行 xhr 發(fā)送請求的 Promise 對象。

給我們的 Axios.js 添加發(fā)送請求的方法: 

  1. //Axios.js  
  2. import getDefaultAdapter from './adapter.js';  
  3. Axios.prototype.request = function(config){  
  4.     const adapter = getDefaultAdapter(config);  
  5.     var promise = Promise.resolve(config);  
  6.     var chain = [adapter, undefined];  
  7.     while(chain.length){  
  8.         promisepromise = promise.then(chain.shift(), chain.shift());  
  9.     }  
  10.     return promise;  

攔截器實現(xiàn)

攔截器的原理在于 Axios.prototype.request 方法中的 chain 數(shù)組,把請求攔截函數(shù)添加到 chain 數(shù)組前面,把響應(yīng)攔截函數(shù)添加到數(shù)組后面。這樣就可以實現(xiàn)發(fā)送前攔截和響應(yīng)后攔截的效果。

創(chuàng)建 InterceptorManager.js 

  1. //InterceptorManager.js   
  2. //攔截器  
  3. function InterceptorManager(){  
  4.     this.handlers = [];  
  5.  
  6. InterceptorManager.prototype.use = function(fulfilled, rejected){  
  7.     this.handlers.push({  
  8.         fulfilled: fulfilled,  
  9.         rejected: rejected  
  10.     });  
  11.     return this.handlers.length -1;  
  12.  
  13. export default InterceptorManager; 

在 Axios.js 文件中,構(gòu)造函數(shù)有 interceptors屬性: 

  1. //Axios.js  
  2. function Axios(config){  
  3.     this.interceptors = {  
  4.         request: new InterceptorManager(),  
  5.         response: new InterceptorManager()  
  6.     }  

這樣我們在 Axios.prototype.request 方法中對攔截器添加處理: 

  1. //Axios.js  
  2. Axios.prototype.request = function(config){  
  3.     const adapter = getDefaultAdapter(config);  
  4.     var promise = Promise.resolve(config);  
  5.     var chain = [adapter, undefined];  
  6.     //請求攔截  
  7.     this.interceptors.request.handlers.forEach(item=> 
  8.         chain.unshift(item.rejected);  
  9.         chain.unshift(item.fulfilled);      
  10.      });  
  11.     //響應(yīng)攔截  
  12.     this.interceptors.response.handlers.forEach(item=> 
  13.         chain.push(item.fulfilled);  
  14.         chain.push(item.rejected)  
  15.     });  
  16.     console.dir(chain);  
  17.     while(chain.length){  
  18.         promisepromise = promise.then(chain.shift(), chain.shift());  
  19.     }  
  20.     return promise;  

所以攔截器的執(zhí)行順序是:請求攔截2 -> 請求攔截1 -> 發(fā)送請求 -> 響應(yīng)攔截1 -> 響應(yīng)攔截2

取消請求

來到 Axios 最精彩的部分了,取消請求。我們知道 xhr 的 xhr.abort(); 函數(shù)可以取消請求。那么什么時候執(zhí)行這個取消請求的操作呢?得有一個信號告訴 xhr 對象什么時候執(zhí)行取消操作。取消請求就是未來某個時候要做的事情,你能想到什么呢?對,就是 Promise。Promise 的 then 方法只有 Promise 對象的狀態(tài)變?yōu)?resolved 的時候才會執(zhí)行。我們可以利用這個特點,在 Promise 對象的 then 方法中執(zhí)行取消請求的操作。看代碼: 

  1. //CancelToken.js  
  2. // 取消請求  
  3. function CancelToken(executor){  
  4.     if(typeof executor !== 'function'){  
  5.         throw new TypeError('executor must be a function.')  
  6.     }  
  7.     var resolvePromise;  
  8.     this.promise = new Promise((resolve)=> 
  9.         resolveresolvePromise = resolve;  
  10.     });  
  11.     executor(resolvePromise)  
  12.  
  13. CancelToken.source = function(){  
  14.     var cancel;  
  15.     var token = new CancelToken((c)=> 
  16.         ccancel = c;  
  17.     })  
  18.     return { 
  19.          token,  
  20.         cancel  
  21.     };  
  22.  
  23. export default CancelToken; 

當(dāng)我們執(zhí)行 const source = CancelToken.source()的時候,source 對象有兩個字段,一個是 token 對象,另一個是 cancel 函數(shù)。在 xhr 請求中: 

  1. //適配器  
  2. // adapter.js  
  3. function xhrAdapter(config){  
  4.     return new Promise((resolve, reject)=> 
  5.         ...  
  6.         //取消請求  
  7.         if(config.cancelToken){  
  8.             // 只有 resolved 的時候才會執(zhí)行取消操作  
  9.             config.cancelToken.promise.then(function onCanceled(cancel){  
  10.                 if(!xhr){  
  11.                     return;  
  12.                 }  
  13.                 xhr.abort();  
  14.                 reject("請求已取消"); 
  15.                  // clean up xhr  
  16.                 xhr = null 
  17.             })  
  18.         }  
  19.     })  

CancelToken 的構(gòu)造函數(shù)中需要傳入一個函數(shù),而這個函數(shù)的作用其實是為了將能控制內(nèi)部 Promise 的 resolve 函數(shù)暴露出去,暴露給 source 的 cancel 函數(shù)。這樣內(nèi)部的 Promise 狀態(tài)就可以通過 source.cancel() 方法來控制啦,秒啊~ 👍

node 后端接口

node 后端簡單的接口代碼: 

  1. const express = require("express");  
  2. const bodyParser = require('body-parser');  
  3. const app = express();  
  4. const router = express.Router();  
  5. //文件下載  
  6. const fs = require("fs");  
  7. // get 請求  
  8. router.get("/getCount", (req, res)=> 
  9.   setTimeout(()=> 
  10.     res.json({  
  11.       success: true,  
  12.       code: 200,  
  13.       data: 100  
  14.     })  
  15.   }, 1000)  
  16. })  
  17. // 二進(jìn)制文件流 
  18. router.get('/downFile', (req, res, next) => {  
  19.   var name = 'download.txt' 
  20.   var path = './' + name;  
  21.   var size = fs.statSync(path).size;  
  22.   var f = fs.createReadStream(path);  
  23.   res.writeHead(200, {  
  24.     'Content-Type': 'application/force-download',  
  25.     'Content-Disposition': 'attachment; filename=' + name,  
  26.     'Content-Length': size  
  27.   });  
  28.   f.pipe(res);  
  29. })  
  30. // 設(shè)置跨域訪問  
  31. app.all("*", function (request, response, next) { 
  32.   // 設(shè)置跨域的域名,* 代表允許任意域名跨域;http://localhost:8080 表示前端請求的 Origin 地址  
  33.   response.header("Access-Control-Allow-Origin", "http://127.0.0.1:5500");  
  34.   //設(shè)置請求頭 header 可以加那些屬性  
  35.   response.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');  
  36.   //暴露給 axios https://blog.csdn.net/w345731923/article/details/114067074  
  37.   response.header("Access-Control-Expose-Headers", "Content-Disposition");  
  38.   // 設(shè)置跨域可以攜帶 Cookie 信息  
  39.   response.header('Access-Control-Allow-Credentials', "true");  
  40.   //設(shè)置請求頭哪些方法是合法的  
  41.   response.header(  
  42.     "Access-Control-Allow-Methods",  
  43.     "PUT,POST,GET,DELETE,OPTIONS"  
  44.   );  
  45.   response.header("Content-Type", "application/json;charset=utf-8");  
  46.   next();  
  47. });  
  48. // 接口數(shù)據(jù)解析  
  49. app.use(bodyParser.json())  
  50. app.use(bodyParser.urlencoded({  
  51.   extended: false  
  52. }))  
  53. app.use('/api', router) // 路由注冊  
  54. app.listen(8081, () => {  
  55.   console.log("服務(wù)器啟動成功!")  
  56. }); 

git 地址

如果大家能夠跟著源碼敲一遍,相信一定會有很多收獲。 

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2023-09-19 22:41:30

控制器HTTP

2024-09-30 08:43:33

HttpgolangTimeout

2021-01-18 05:13:04

TomcatHttp

2025-10-16 09:08:03

2021-04-22 05:37:14

Axios 開源項目HTTP 攔截器

2018-07-30 16:31:00

javascriptaxioshttp

2021-04-12 05:55:29

緩存數(shù)據(jù)Axios

2024-06-05 08:42:24

2024-03-19 08:36:19

2021-04-06 06:01:11

AxiosWeb 項目開發(fā)

2025-02-06 08:09:20

POSTGET數(shù)據(jù)

2019-12-13 09:14:35

HTTP2協(xié)議

2021-07-23 15:55:31

HTTPETag前端

2021-05-26 05:18:51

HTTP ETag Entity Tag

2024-04-30 09:53:12

axios架構(gòu)適配器

2018-10-18 10:05:43

HTTP網(wǎng)絡(luò)協(xié)議TCP

2019-04-08 15:11:12

HTTP協(xié)議Web

2024-08-12 12:32:53

Axios機制網(wǎng)絡(luò)

2021-06-02 05:41:48

項目實踐Axiosaxios二次封裝

2019-07-02 08:24:07

HTTPHTTPSTCP
點贊
收藏

51CTO技術(shù)棧公眾號