• 解决 vite 4 开发环境和生产环境打包后空白、配置axios跨域、nginx代理本地后端接口问题


    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)这里有解释

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

    然后在vite.config.js中添加

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

    在request.js中 添加 

    baseURL: import.meta.env.VITE_API_BASE_URL,

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

    3、nginx 代理跨域 

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

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

    找到配置文件

    在配置文件中

    1. location / {
    2. root html/dist; //这里是你打包生产环境的包地址
    3. index index.html index.htm;
    4. }
    5. #error_page 404 /404.html;
    6. # redirect server error pages to the static page /50x.html
    7. #
    8. error_page 500 502 503 504 /50x.html;
    9. location = /50x.html {
    10. root html;
    11. }
    12. # 反向代理
    13. location /api/ {
    14. proxy_pass http://localhost:8080/admin/;
    15. #proxy_pass http://webservers/admin/;
    16. }

     重启nginx就可以了 

    开发环境 pnpm dev 后 前端请求

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

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

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

     此时请求地址是

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

  • 相关阅读:
    Android log 系统
    FAST协议详解4 存在图PMap
    我的四核Cortex-A53学习之路
    UART相关参数和Modbus协议
    2 JavaScript in HTML
    基于SSH开发高列火车票票务查询订购系统
    DPDK helloworld示例程序
    JVM是启动过程是怎样的?
    StringTable
    【翻译】Efficient Data Loader for Fast Sampling-Based GNN Training on Large Graphs
  • 原文地址:https://blog.csdn.net/ClearloveYt/article/details/134462707