最近项目开始前后端联调,需要部署测试服,结果打包部署上去后axios访问路径一直不对,本地用的proxyTable代理解决的跨域,部署的时候每次手动改路径会比较麻烦,于是各种百度出解决方法:

将config/prod.env.js中,新增:

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_HOST:'http://XXXXXXXX/'
}

将config/dev.env.js中,新增:

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_HOST:"/api/"
})

在main.js中,设置:

axios.defaults.baseURL = process.env.API_HOST;

在组件中调接口时候:

this.$axios.post('login',this.$qs.stringify({username:this.form.username,password:this.form.passwd}))

这样最终运行npm run dev是OK的,但是npm run build的时候就一直报错:

ERROR in chunk app [initial]
static/js/[name].[chunkhash].js
Unexpected token (47:27)
|       var that = this;
|       this.$axios.post(http://xxxxxxx/ + 'login', this.$qs.stringify({ username: this.form.username, password: this.form.passwd })).then(function (response) {
|         if (response.status === 200) {
|           var data = that.$qs.parse(response.data);

ERROR in static/js/vendor.a8df6eb4f03839ea7474.js from UglifyJs
Unexpected token punc «:», expected punc «,» [static/js/vendor.a8df6eb4f03839ea7474.js:53256,103]

  Build failed with errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! suanlib@1.0.0 build: `node build/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the suanlib@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     D:\nodeJs\node_cache\_logs\2020-03-31T00_58_38_842Z-debug.log

百思不得其解,一直翻来覆去检查,以为是调用接口的地方写错了什么符号之类的。最后第二天试着根据提示的[static/js/vendor.a8df6eb4f03839ea7474.js:53256,103],打开这个文件才发现,原来是config/prod.env.js中配置的API_HOST,少加了个双引号,导致最后编译出错。写此文告诫自己记住,此处正确写法应该是:

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_HOST:'"http://XXXXXXXX/"'
}

一定要单双引号全部加上!!!!

 

参考链接:https://www.jianshu.com/p/87b5475a101a

Logo

前往低代码交流专区

更多推荐