vue项目上线打包后出现的问题

avatar
作者
筋斗云
阅读量:0

1、出现空白页

1.1 打包路径: module.exports = {     publicPath:'./',    //修改为绝对路径 }

         修改完打包路径后build可以展示页面

        1.2 路由模式:
                项目上线要求是history模式,需要后端做重定向
                前端自测可以使用hash模式 

2、代理和环境变量

问题:打包前可以获取数据,build后打开就报错了

 vue-cli中文官网Vue CLI

解决:

        2.1 在根目录新建文件.env.production

VUE_APP_TITLE = 'cwc'  VUE_APP_ENV = 'pro'  VUE_APP_BASE_API = 'http://localhost:3000/'

        2.2 新建文件.env.development

VUE_APP_TITLE = 'cwc'  VUE_APP_ENV = 'dev'  VUE_APP_BASE_API = 'http://localhost:3000/'

         2.3 封装下axios  src/api/http.js

import axios from "axios";  export default {     $axios(option) {         let apiUrl = null;         if (process.env.VUE_APP_ENV === 'dev') {             apiUrl = option.url         } else {             apiUrl = process.env.VUE_APP_BASE_API + option.url         }         console.log(apiUrl, 'apiUrl');         return axios({             url: apiUrl         })     } }

        2.4 组件中调用接口

<script> import http from "../api/http"; export default {   name: 'HelloWorld',   props: {     msg: String   },   created() {     http.$axios({       url: 'list'     }).then(res => {       console.log(res)     })   } } </script>

        2.5 vue.config.js 中已做的配置(保证配置后能正常获取接口数据,且build后不会出现空白页)

const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({   publicPath:'./',   transpileDependencies: true,   devServer: {     proxy: 'http://localhost:3000'   }, })

        2.6 如果做了以上配置build后还是无法获取数据,可尝试在后端配置以下代码

router.all('*', function (req, res, next) {   res.header('Access-Control-Allow-Origin', '*');   res.header('Access-Control-Allow-Headers', 'Content-Type');   res.header('Access-Control-Allow-Methods', '*');   res.header('Content-Type', 'application/json;charset=utf-8');   next(); })

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!