1、解决打包本地无法访问空白 

首先是pnpm  build 打包后直接在dist访问,是访问不了的,需要开启服务

终端输入 npm install -g serve  然后再输入 serve -s dist  就可以访问了

 但要保证 路由模式是:createWebHashHistory

 和vite.conffig.js中添加 

2、解决配置axios跨域

 首先

前端请求地址:http://localhost/api/employee/login

后端接口地址:http://localhost:8080/admin/employee/login

npm run dev 后前端是无法请求到后端接口的 

首先在根下 新建.env.development 和 .env.production  环境变量和模式 | Vite 官方中文文档 (vitejs.dev)这里有解释

# .env.development
VITE_API_BASE_URL=http://localhost:8888/api

# .env.production
VITE_API_BASE_URL=http://localhost/api

然后在vite.config.js中添加

server: {
    host: '0.0.0.0',
    port: 8888, //这里的端口跟配置开发环境文件# .env.development的端口要一致
    proxy: {
      '/api': {
        target:  'http://localhost:8080',//这里是后端的接口
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '/admin')
      }
    }
  },

在request.js中 添加 

baseURL: import.meta.env.VITE_API_BASE_URL,

 同时按需导出的baseURL也不需要了

3、nginx 代理跨域 

配置上面的之后还有配置ngxin  下载合适版本nginx:下载

 下载后放在没有中文的目录中

找到配置文件

在配置文件中

location / {
            root   html/dist; //这里是你打包生产环境的包地址
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # 反向代理
        location /api/ {
			proxy_pass   http://localhost:8080/admin/;
            #proxy_pass   http://webservers/admin/;
        }
		

 重启nginx就可以了 

开发环境 pnpm dev 后 前端请求

反向代理 就可以请求到后端的 8080/admin  了

生产环境 通过pnpm build  项目中就多了 dist 文件夹 ,将它复制到nginx html下 

点击nginx.exe   在浏览器中输入localhsot 就能访问前端代码  当然前提你nginx配置的就是80 也可以是其他端口 , 要跟生产环境配置文件的 端口一致

 此时请求地址是

这样通过反向代理就可以 请求到后端数据。

Logo

一站式 AI 云服务平台

更多推荐