一、修改Vue2项目端口号
方法1:通过package.json配置(推荐)
// package.json
{
"scripts": {
"serve": "vue-cli-service serve --port 8081",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
}
运行命令:
npm run serve # 将在8081端口启动
方法2:通过vue.config.js配置
// vue.config.js
module.exports = {
devServer: {
port: 8081, // 设置端口号为8081
host: 'localhost', // 指定主机
open: true, // 启动后自动打开浏览器
https: false // 是否使用https
}
}
方法3:命令行参数临时修改
# 临时指定端口
npm run serve -- --port 8081
# 或使用完整命令
vue-cli-service serve --port 8081 --host 0.0.0.0
方法4:环境变量配置
创建.env.development文件:
# .env.development
PORT=8081
HOST=localhost
二、配置后端代理
基础代理配置
// vue.config.js
module.exports = {
devServer: {
port: 8081,
// 代理配置
proxy: {
// 代理所有以/api开头的请求
'/api': {
target: 'http://localhost:3000', // 后端服务器地址
changeOrigin: true, // 是否改变源地址
pathRewrite: {
'^/api': '' // 重写路径,移除/api前缀
}
}
}
}
}
多代理配置
// vue.config.js
module.exports = {
devServer: {
port: 8081,
proxy: {
// 用户服务代理
'/user-api': {
target: 'http://localhost:3001',
changeOrigin: true,
pathRewrite: {
'^/user-api': '/api'
}
},
// 商品服务代理
'/product-api': {
target: 'http://localhost:3002',
changeOrigin: true,
pathRewrite: {
'^/product-api': '/api'
}
},
// 文件上传代理
'/upload': {
target: 'http://localhost:3003',
changeOrigin: true
}
}
}
}
完整示例:带WebSocket和详细配置
// vue.config.js
const path = require('path')
module.exports = {
devServer: {
port: 8081,
host: 'localhost',
open: true,
hot: true, // 热更新
compress: true, // 开启gzip压缩
overlay: { // 错误显示在页面上
warnings: true,
errors: true
},
headers: {
'Access-Control-Allow-Origin': '*',
},
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
secure: false, // 如果是https接口,需要配置这个参数
pathRewrite: {
'^/api': ''
},
logLevel: 'debug', // 打印代理日志
// 自定义代理响应头
onProxyRes: function(proxyRes, req, res) {
proxyRes.headers['x-proxy-by'] = 'vue-cli';
}
},
// WebSocket代理
'/ws': {
target: 'ws://localhost:3001',
ws: true, // 启用WebSocket代理
changeOrigin: true,
pathRewrite: {
'^/ws': ''
}
}
}
}
}
三、在项目中使用代理
1. 配置axios
// src/utils/request.js
import axios from 'axios'
// 创建axios实例
const service = axios.create({
baseURL: process.env.NODE_ENV === 'development' ? '/api' : 'https://api.yourdomain.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
service.interceptors.request.use(
config => {
// 在发送请求之前做些什么
const token = localStorage.getItem('token')
if (token) {
config.headers['Authorization'] = 'Bearer ' + token
}
return config
},
error => {
// 对请求错误做些什么
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response => {
// 对响应数据做点什么
return response.data
},
error => {
// 对响应错误做点什么
return Promise.reject(error)
}
)
export default service
2. 在组件中使用
// src/api/user.js
import request from '@/utils/request'
export function login(data) {
return request({
url: '/auth/login',
method: 'post',
data
})
}
export function getUserInfo() {
return request({
url: '/user/info',
method: 'get'
})
}
// src/views/Login.vue
<script>
import { login } from '@/api/user'
export default {
methods: {
async handleLogin() {
try {
const result = await login({
username: this.username,
password: this.password
})
console.log('登录成功:', result)
} catch (error) {
console.error('登录失败:', error)
}
}
}
}
</script>
四、常见问题解决方案
1. 代理不生效
检查步骤:
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
logLevel: 'debug', // 添加这行查看代理日志
onProxyReq: (proxyReq, req, res) => {
console.log('代理请求:', req.url)
}
}
}
}
}
2. 跨域问题
如果代理后仍有跨域问题:
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
// 设置CORS头
onProxyRes: function(proxyRes) {
proxyRes.headers['Access-Control-Allow-Origin'] = '*'
proxyRes.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE'
proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
}
}
}
}
3. 配置区分环境
// vue.config.js
const targetMap = {
development: 'http://localhost:3000',
test: 'http://test-api.example.com',
production: 'https://api.example.com'
}
module.exports = {
devServer: {
port: process.env.VUE_APP_PORT || 8081,
proxy: {
'/api': {
target: targetMap[process.env.NODE_ENV] || targetMap.development,
changeOrigin: true
}
}
}
}
五、其他相关配置
1. 环境变量配置
# .env.development
VUE_APP_API_BASE=/api
VUE_APP_WS_BASE=/ws
PORT=8081
2. 使用配置文件
// config/proxy.config.js
module.exports = {
dev: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
},
test: {
'/api': {
target: 'http://test-api.example.com',
changeOrigin: true
}
}
}
// vue.config.js
const proxyConfig = require('./config/proxy.config.js')
module.exports = {
devServer: {
port: 8081,
proxy: proxyConfig[process.env.NODE_ENV] || proxyConfig.dev
}
}
总结
通过上述配置,您可以:
✅ 轻松修改Vue2项目的运行端口
✅ 配置多环境的后端代理
✅ 解决开发环境跨域问题
✅ 实现更复杂的代理需求
记得修改配置后需要重启开发服务器:
npm run serve
如果遇到任何问题,检查浏览器控制台和终端日志,通常会有详细的错误提示。