一個最簡單的代理例子:index.html中有以下代碼html
fetch('/api/pub/article/list?pageSize=2').then((data)=>{ return data.json() }).then((json)=>{ console.log(json) })
裏面訪問的是相對地址,但我本地並無服務器有提供這些api。把以上的路徑補全爲雲服務器上的絕對路徑,可是又報CORS錯誤。webpack
解決辦法是配置一個代理。這裏經過webpack-dev-server實現,簡單的配置文件以下:web
module.exports = { entry: { bundle:'./main.js', }, output: { filename: '[name].js' }, devServer: { port: 8889, host: '127.0.0.1', proxy: { '/api/*': { target: 'http://123.207.95.11:9001' } } } };
接着運行(以當前目錄做爲靜態文件的根目錄):json
webpack-dev-server --content-base ./
訪問 http://127.0.0.1:8889/index.html ,以上代碼能夠正常執行了。api
對於以上的配置和運行指令,作了以下事情:瀏覽器