使用python库uvicorn替代Nginx发布Vue3项目

目录

一、Vue3项目打包

二、将打包文件放到python项目

三、配置uvicorn服务

四、启动服务


【SpringBoot版传送门:使用SpringBoot替代Nginx发布Vue3项目_苍穹之跃的博客-CSDN博客

一、Vue3项目打包

(博主vue版本:3.2.44)

由于是要放在FastAPI中,接口服务和Web服务用的是同一个端口,所以我们给前端一个统一的URL前缀来区分前端页面和后端接口。比如:/admin;配置方式如下:在src/router文件夹下找到路由文件,注意要用history模式,不要用哈希。

至于打包,就跟平时打包到nginx一样的去打包就行了。(不要添加base参数,画蛇添足!)

二、将打包文件放到python项目

在python项目中新建文件夹static,然后将打包好的vue包复制进去。

三、配置uvicorn服务

新建api_service.py文件作为入口类

①静态文件映射

②配置VueRouter路由的反向代理

③强制让JS文件的MIME类型为application/javascript

完整代码如下↓↓↓

python 复制代码
import uvicorn
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import HTMLResponse

app = FastAPI()

app.mount("/", StaticFiles(directory="static"), name="/")


# 静态文件代理
class RedirectToIndexMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # 排除静态文件
        if not request.url.path.endswith((".js", ".css", ".png", ".ico")):
            # 只拦截指定前缀
            if request.url.path.startswith("/admin/") or request.url.path == "/admin":
                return HTMLResponse(content=request.app.index_html, status_code=200)
        response = await call_next(request)
        return response


# 读取index.html
with open("static/index.html", encoding='utf-8') as f:
    app.index_html = f.read()
# 添加中间件
app.add_middleware(RedirectToIndexMiddleware)


# 自定义JS文件的MIME类型为application/javascript
@app.middleware("http")
async def override_static_file_mimetype(request, call_next):
    response = await call_next(request)
    if request.url.path.endswith((".js")):
        response.headers["content-type"] = "application/javascript"
    return response


# 添加中间件
app.add_middleware(RedirectToIndexMiddleware)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

四、启动服务

浏览器访问:http://localhost:8000/admin

相关推荐
fo安方28 分钟前
运维的利器–监控–zabbix–第三步:配置zabbix–中间件–Tomcat–步骤+验证
运维·中间件·zabbix
超喜欢下雨天1 小时前
服务器安装 ros2时遇到底层库依赖冲突的问题
linux·运维·服务器·ros2
搬码临时工1 小时前
小企业如何搭建本地私有云服务器,并设置内部网络地址提供互联网访问
运维·服务器
18你磊哥2 小时前
Windows 本地安装部署 Apache Druid
运维·debian
IT成长日记3 小时前
【Docker基础】Docker数据卷管理:docker volume inspect及其参数详解
运维·docker·容器·volume·inspect
ldj20203 小时前
Jenkins 构建过程常见错误
运维·jenkins
ladymorgana3 小时前
【Docker】如何设置 `wiredTigerCacheSizeGB` 和 `resources.limits.memory`
运维·docker·容器
chanalbert4 小时前
CentOS系统新手指导手册
linux·运维·centos
星宸追风4 小时前
Ubuntu更换Home目录所在硬盘的过程
linux·运维·ubuntu
制造数字化方案研究院5 小时前
59页|PPT|华为集成服务交付ISD业务变革总体方案:业务规则、流程、IT、组织及度量“四位一体”的管理体系
运维·华为