vue3打包上线后后台接口404错误(vue3.11版本)

vue项目在开发模式时,使用的axios调用的后台接口,而使用axios调用后台接口,需要在vue.config.js中配置proxy代理,否则会出现请求头错误,而设置了proxy代理后,vue项目打包proxy代理就会失效,因为proxy代理并不会一起打包到dist文件夹下,网上的说法都是配置不同环境新建env文件及更换baseurl等,但是我发现这种做法在vue3.11版本中并不适用,直接根据打包环境更换baseurl还是会导致项目出现请求头问题,也有可能是我配置有问题,但我确实无法通过那些方法解决,所以改用nginx服务器发布,通过对nginx目录中conf文件夹下nginx.conf文件设置反向代理,完全可以不用更改vue项目的后台接口地址,以下是vue项目中关于后台接口及反向代理的代码:
App.vue:

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

<script>
export default {
  data(){
    return{

    }
  },
  created(){
    this.$axios.get("/two/three?four=4")
      .then(res =>{
        console.log(res.data);
      })
  }
}
</script>

vue.config.js:

module.exports = {
    publicPath:'./',
    devServer:{
        proxy:{
            '/two':{
                target:'http://10.10.10.10:8080/',
            }
        }
    }
}

main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$axios = axios

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

以下是nginx.conf文件中添加了以下代码:

location ^~/two/ {
	rewrite ^/(.*)$ /$1 break;
	proxy_pass http://10.10.10.10:8080/;
}

如果有多条代理可以这样设置:

location ^~/two/ {
	rewrite ^/(.*)$ /$1 break;
	proxy_pass http://10.10.10.11:8080/;
}
location ^~/three/ {
	rewrite ^/(.*)$ /$1 break;
	proxy_pass http://10.10.10.12:8080/;
}
location ^~/four/ {
	rewrite ^/(.*)$ /$1 break;
	proxy_pass http://10.10.10.13:8080/;
}

以上就是解决vue3打包后调用后台接口404的解决办法,关于更多vue3打包上线的坑,可以查看这篇博客:
vue3.11打包上线时遇到的坑(打包后页面空白、接口404、进入二级页面刷新404)

你可能感兴趣的:(vue3,vue3打包上线)