需求:
vue项目运行后自动生成了端口号,在项目中没有搜寻到端口设置;同时跨域需要设置代理。
网上:
如果是 Webpack打包,在项目根目录(与package.json同级)新建vue.config.js文件进行配置。
文件内容如下:
module.exports = {
publicPath: "/", //根路径 Vue CLI 3.3 前使用 baseUrl
outputDir: "dist", //构建输出目录
assetsDir: "assets", //静态资源目录
lintOnSave: false, //是否开启eslint保存检测
runtimeCompiler: true,
publicPath: "/", // 设置打包文件相对路径
devServer: {
host: '0.0.0.0',
port: 8088,
open: true,//vue项目启动时自动打开浏览器
proxy: {
'/urlApi': {
target: 'http://localhost:8060', //接口域名
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
secure: true, //是否https接口
pathRewrite: { //路径重置
'^/urlApi': ''
}
}
}
}
};
但是不生效,检查package.json文件,发现配置信息设置在了vite.config.ts。
因为打包工具用的是 Vite 不是 Webpack。
在vite.config.ts没有配置端口信息,在Serve里设置,同时设置前端代理。
server:{
host:'0.0.0.0',
port:4000, //设置服务启动端口
// open:true, //设置服务启动时是否自动打开浏览器
cors:true, //允许跨域
//设置代理
proxy:{
// 字符串简写写法
// '/api': 'http://localhost:8060',
// // 选项写法
// '/urlApi':{
// target:'http://localhost:8060',
// changeOrigin: true, //是否跨域
// ws: true, //是否代理 websockets
// secure: true, //是否https接口
// // rewrite:(path) => path.replace('/urlApi/','/')
// rewrite: (path) => path.replace(/^\/urlApi/, '')
// },
// 正则表达式写法
'^/urlApi/.*': {
target: 'http://localhost:8060',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/urlApi/, '')
},
}
}
端口号果然改成了4000
这里如果是path为根路径加上 /urlApi 就会替代target里的地址。