详解vue+axios给开发环境和生产环境配置不同的接口地址

2020-06-13 10:46:09易采站长站整理

为什么要配置不同的接口地址

在开发过程中,前端请求访问的是自己本机启动的后台服务,此时涉及到跨域(因为端口不一样),所以在config/index.js文件中配置了代理


//检查某个文件是否存在
try {
fs.statSync(path.join(__dirname, '../proxy/' + templatedir + '.json'))
//如果可以执行到这里那么就表示存在了
console.log(124)
proxyTable = require('../proxy/' + templatedir + '.json')
} catch (e) {
//捕获异常'
}
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: proxyTable,

// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
index: templatedir,
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
}

然后再proxy文件夹里建立对应的项目名.json文件,


{
"/": {
"target": "", // 被请求的地址
"changeOrigin": true,
"pathRewrite": {
"^/": "/"
}
}
}

注意:proxyTanle这个插件只限于开发模式下,后面一定要将前端代码和服务器代码部署在一起,负责需要通过Nginx进行跨域的转发配置。