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

文檔資料

webpack關於webpack-dev-server開啓proxy的官方介紹
Vue-cli proxyTable 解決開發環境的跨域問題——雖然這篇是寫vue的,不過用在webpack-dev-server上也是一樣的
webpack設置代理
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://m.qtour.next.qulv.com',    //要跳轉的域名
 changeOrigin: true,
 secure: false
 }
 }
 },

 ...此處省略一萬字
};

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

調用接口

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

$.ajax({
 // url: 'http://m.qtour.next.qulv.com/api/v2/Search/Suggestion', // 這樣不行
 url: '/api/v2/Search/Suggestion', // 這樣行
 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'
  • 結合上面的 “調用接口” 可以看出, url: '/test/testFetch/Login.php' 這句,實際上會自動補充前綴,也就是說,url: '/test/testFetch/Login.php' 等價於 url: 'http://10.0.0.9:3000/test/testFetch/Login.php'
  • 但是,我們使用了http-proxy進行重定向,這樣的話,url: '/test/testFetch/Login.php' 等價於 url: 'http://localhost/test/testFetch/Login.php'

changeOrigin

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

secure

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

pathRewrite

  • 例子: pathRewrite: {'^/api': ''}
  • Object-keys will be used as RegExp to match paths
  • 我猜,這裏是將 '^/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對象

小禮物走一走,來簡書關注我



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章