起因:为了便于前端进行测试,有时需要进行本地代理;
本地代理与反向代理是冲突的,若要同时使用本地代理和反向代理,需要进行以下配置:
在build文件夹下的webpack-dev-conf.js文件中配置
1)在const portfinder = require('portfinder')后面添加下面代码:
//声明变量接收express组件 const express = require('express'); //请求server,赋值espress函数 var app = express(); //加载本地数据 var homeData = require('../src/data/homeData.json'); var movieData = require('../src/data/movieData.json'); //配置路由文件 var apiRoutes = express.Router(); //通过路由请求数据 app.use('/api',apiRoutes);
2)在webpack配置文件的devServer选项里添加before()方法
const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js devServer: { clientLogLevel: 'warning', historyApiFallback: { rewrites: [ { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, ], }, hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, }, before(app){ app.get('/api/homeData',function(req,res){ res.json({ errno:0, data:homeData }) }), app.get('/api/movieData',function(req,res){ res.json({ errno:0, data:movieData }) }) } }
3)在vue文件中调用
getMovieData:function(){ this.axios.get('/api/movieData',{}).then((data)=>{ console.log(data); this.title = data; }) } //================= getHomeData:function(){ this.axios.get('/api/homeData',{}).then((data)=>{ console.log(data); }) }