文章目录
- 概要
- 前端Umi项目
- 配置文件
- 请求后端Api
- 打包
- 后端项目
- Nginx配置
- 配置文件
- 错误信息
概要
使用UmiJs开发的前端项目打包部署在Nginx,主要是Umi中项目的配置和Nginx的配置
前端Umi项目
基于"@umijs/max": "^4.3.24", + "react": "^18.3.1"
配置文件
./.umirc.ts
import { defineConfig } from '@umijs/max';
export default defineConfig({npmClient: 'yarn',esbuildMinifyIIFE: true,base: '/web/',publicPath: '/web/',favicons: ['/src/assets/favicon.png'],
});
注意文件中的 /web/
请求后端Api
./src/utils/util.tsx
import { request as umiRequest } from 'umi';
const request = (url: string, options?: RequestConfig) => {return umiRequest('/api' + url, {...options,});
};
注意文件中的 /api,最终的url应该是 /api/url 形式,即调用 request 方法的时候传参 url 应该是以 / 开头
打包
./package.json
{"scripts": {"build": "max build",},
}
- > yarn build
- > ./dist
后端项目
普通的提供Restful Api的Http服务端即可
- > 8888
- > 前端项目能正常访问
Nginx配置
版本:1.26.3
配置文件
./conf/nginx.conf
http {include mime.types;default_type application/octet-stream;server {listen 80;server_name localhost;# 后端Api配置location /api/ {proxy_pass http://localhost:8888/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;}# 前端项目打包后产生dist,将dist重命名为web,放置到/tmp下# 即 /tmp/web 对应下面的配置# 注意 /web /web/index.html 这些和前端打包时对应一致,否则会出现错误,在浏览器控制台查看location /web {# root /usr/local/nginx/html;root /tmp;index index.html;try_files $uri /web/index.html;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
}
错误信息
由于不满足以上所有配置而出现的错误信息
Uncaught SyntaxError: Unexpected token '<' (at preload_helper.js:1:1)Understand this errorAI
umi.js:1 Uncaught SyntaxError: Unexpected token '<' (at umi.js:1:1)
查看浏览器请求响应,这个对应请求JS资源的响应尽然返回的是HTML,且是 dist/index.html
的内容,在页面报错需要关注 nginx
的 error.log
日志信息方便查错