Vue项目部署后,API请求路径从预期的远程服务器地址变成了本地路径(如http://localhost:8080/api
),导致请求失败。
查看项目中的环境变量文件:
- .env
- 通用环境变量
- .env.development
- 开发环境变量
- .env.production
- 生产环境变量
确保生产环境变量文件中有正确的API基础URL:
VUE_APP_API_BASE_URL=https://api.yourdomain.com
查看axios或其他HTTP客户端的配置:
// 通常应该这样配置
const instance = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL
});
开发环境可能使用了代理配置,但生产环境不会使用这些配置:
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', // 这只是开发环境使用
changeOrigin: true
}
}
}
}
运行npm run build
后,检查dist
目录下的文件,搜索API地址是否正确替换。
创建/修改.env.production
文件:
VUE_APP_API_BASE_URL=https://api.yourdomain.com
在代码中使用:
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
对于需要更灵活配置的场景:
在public
目录下创建config.json
:
{
"apiBaseUrl": "https://api.yourdomain.com"
}
在应用启动时加载配置:
async function loadConfig() {
const response = await fetch('/config.json')
const config = await response.json()
axios.defaults.baseURL = config.apiBaseUrl
}
如果API与前端同域,可以使用相对路径:
axios.get('/api/users') // 会自动使用当前域名
dist/js/app.*.js
文件,搜索API地址是否正确serve
测试生产构建:
bash
npm install -g serve
serve -s dist
VUE_APP_
前缀的变量通过以上步骤,应该能够解决Vue项目部署后API请求路径变成本地路径的问题。