国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

詳解webpack-dev-server使用http-proxy解決跨域問題

2024-05-06 16:41:58
字體:
來源:轉載
供稿:網友

文檔資料

webpack關于webpack-dev-server開啟proxy的官方介紹

Vue-cli proxyTable 解決開發環境的跨域問題——雖然這篇是寫vue的,不過用在webpack-dev-server上也是一樣的

http-proxy-middleware——webpack-dev-server的實現方法其實是對這個的封裝

配置http-proxy

在webpack的配置文件(webpack.config.js)中進行配置

module.exports = { ...此處省略一萬字 // webpack-dev-server的配置 devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, port: 3000, host: '10.0.0.9', proxy: { '/test/*': { target: 'http://localhost', changeOrigin: true, secure: false } } }, ...此處省略一萬字};

上述配置中,關于http-proxy的只是 proxy: {...} 中的值

調用接口

為了方便起見,下面使用jquery封裝好的ajax函數進行示范

$.ajax({ // url: 'http://10.0.0.9:3000/test/testFetch/Login.php', // 這樣不行 url: '/test/testFetch/Login.php', // 這樣行 type: 'post', data: { app_id: '13751313169', password: '123456', user_name: 'Nicholas' }, success: function(data) { console.log(data); }});

proxy中的部分參數說明

'/test/*' 以及 target: 'http://localhost'

從名字就能看出,這個實際上是將匹配 '/test/*' 這種格式的API的域名重定向為 'http://localhost'

  1. 結合上面的 “調用接口” 可以看出, url: '/test/testFetch/Login.php' 這句,實際上會自動補充前綴,也就是說,url: '/test/testFetch/Login.php' 等價于 url: 'http://10.0.0.9:3000/test/testFetch/Login.php'
  2. 但是,我們使用了http-proxy進行重定向,這樣的話,url: '/test/testFetch/Login.php' 等價于 url: 'http://localhost/test/testFetch/Login.php'

changeOrigin

  1. true/false, Default: false - changes the origin of the host header to the target URL
  2. 本地會虛擬一個服務端接收你的請求并代你發送該請求——這個是別人的說法
  3. 我試了一下,就算這個參數設置成 false 也有部分情況是可以的,具體原因不詳,所以還是將其設置成 true 吧

secure

  1. true/false, if you want to verify the SSL Certs

pathRewrite

  1. 例子: pathRewrite: {'^/api': ''}
  2. Object-keys will be used as RegExp to match paths
  3. 我猜,這里是將 '^/api' 使用 '' 代替(只是我猜,沒是成功,估計是我的正則表達式寫得不行)

附上使用Fetch API的代碼

上述代碼與 “調用接口” 中使用 $.ajax() 實現的效果是一樣的

let testAsync = async function () { var feeling = { app_id: '13751313169', password: '123456', user_name: 'Nicholas' }; var fetchParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, credentials: 'include', // 將憑證也帶上(例如cookies) body: JSON.stringify(feeling), }; let temp = await fetch('/test/testFetch/Login.php', fetchParams).then(response => response.text()); console.log(temp); // 這個就是一個json對象 return temp;};let data = testAsync(); // async函數返回值是一個Promise對象console.log(data); // 這個是一個Promise對象

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洛南县| 老河口市| 金阳县| 囊谦县| 涿州市| 东明县| 海阳市| 绵竹市| 高淳县| 福鼎市| 武山县| 山西省| 宁南县| 胶南市| 田阳县| 札达县| 石泉县| 衢州市| 临朐县| 恩施市| 阿坝| 马关县| 宁波市| 宁明县| 盘锦市| 台前县| 阿坝| 汝南县| 阿克苏市| 建阳市| 潮安县| 从江县| 黑河市| 五台县| 永兴县| 西峡县| 嘉黎县| 吕梁市| 梓潼县| 那曲县| 浑源县|