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

发布时间 2023-11-23 10:01:37作者: pu369com

一、Vue3项目打包

(博主vue版本:4.3.1)

由于是要放在FastAPI中,接口服务和Web服务用的是同一个端口,所以我们给前端一个统一的URL前缀来区分前端页面和后端接口。比如:/admin;配置方式如下:在src/router文件夹下找到路由文件,注意要用history模式,不要用哈希。
至于打包,就跟平时打包到nginx一样的去打包就行了。(不要添加base参数,画蛇添足!)

1.在项目的根目录的终端下输入:

npm init vue@latest

起好目录的名字:vue3,然后一路回车即可.

  cd vue3
  npm install
  npm run dev

一切正常的话,就会看到前端的vue3的欢迎界面了

2.打包vue3项目

在vue3的终端下打包前端项目:

npm run build

目录下会生成一个dist的目录,这个目录就是打包后的前端文件

二、fastapi 环境搭建 

pip install "fastapi[all]"

然后在fastapi目录中创建main.py的入口文件

from fastapi import FastAPI
import uvicorn as uvicorn

@app.get('/test')
def test():
    return 'fastapi + vue3'

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, )

运行该文件,可以看到fastapi的后端环境搭建完毕.

二、vue3项目整合到fastapi

1.在fastapi目录下新建static目录,将vue打包的dist目录中的所有内容,复制到static目录下

修改main.py代码如下:

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)

现在运行main.py,并访问:http://localhost:8000/admin,如果一切正常的话,就会看到前端的vue3的欢迎界面了

关于前后端通讯,可以看我的前一篇文章  关于FastAPI与Vue3的通信 (https://www.cnblogs.com/pu369/p/17850000.html)

 

 

参考:https://blog.csdn.net/wenxingchen/article/details/131978476

https://blog.csdn.net/bosivip/article/details/128141950