不清楚vue.config.js中proxy的设置,花了功夫弄明白了,前后台怎样配置好,前台能请求到后台的服务,具体如下:
1、依据(见参考链接中WebPack官网说明)
devServer.proxy
object [object, function]
Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.
The dev-server makes use of the powerful http-proxy-middleware package. Check out its documentation for more advanced usages. Note that some of http-proxy-middleware’s features do not require a target key, e.g. its router feature, but you will still need to include a target key in your configuration here, otherwise webpack-dev-server won’t pass it along to http-proxy-middleware).
With a backend on localhost:3000, you can use this to enable proxying:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': 'http://localhost:3000'
}
}
};
A request to /api/users will now proxy the request to http://localhost:3000/api/users.
If you don’t want /api to be passed along, we need to rewrite the path:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {'^/api' : ''}
}
}
}
};
2、实例(我自己的实例)
(1)前端请求
原前端请求结构:http://localhost:port/vue-element-admin/sign/logInfo
(2)后台服务
后台yml文件中的配置
server:
servlet:
context-path: /api
port: 8080
即后台服务地址:http://localhost:8080/api
(3)前端vue.config.js中proxy的配置
const port = process.env.port || process.env.npm_config_port || 8082 // dev port
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/geo/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
// before: require('./mock/mock-server.js'),
devServer: {
host: 'localhost', //target host
port: port,//端口号
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {//代理设置
'/vue-element-admin': {//原始请求URL为http://localhost:port/vue-element-admin
target: 'http://localhost:8080',//代理转发到:http://localhost:8080/
pathRewrite: {'^/vue-element-admin': '/api'}//替换后为:http://localhost:8080/api/
}
}
},
(4)效果
target设置将http://localhost:8082/vue-element-admin替换为http://localhost:8080/
pathRewrite将http://localhost:8082/vue-element-admin替换为http://localhost:8080/api
前端请求:http://localhost:8082/vue-element-admin/sign/logInfo
被代理后:http://localhost:8080/api/sign/logInfo
(5)配置的关键
将pathRewrite和target设置成跟后台提供服务的路由一致
3、不生效的试用解决方法
正确设置完毕后,热加载没有Ctrl+C停止node.js,发现请求一直不对,来回改了好久,最终还是确定设置正确,才想到停止前端,重新yarn run dev,启动前端后,生效了
4、参考链接:
https://github.com/chimurai/http-proxy-middleware#proxycontext-config