背景

有时候需要将大的数据通过数据形式传输给后端,比如在js中,我需要将js的json数据发送给给fastapi后端做处理。那么应该怎么做?

后端部分

创建一个test.py文件,并且写入下面代码:


from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
import uvicorn
import datetime

from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()

origins = ["*"]
 
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "Hello World", "datetime": datetime.datetime.now(), "test": 'this is a test'}


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}


if __name__ == '__main__':
    uvicorn.run(app='test:app', reload=True, debug=True)

运行上面的代码:

python test.py

前端部分

这里直接写一个html文件,然后就可以运行

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>test</h1>
    <script>
        const person = {
            name: 'apple',
            description: 'this is a test',
            price:200,
            tax: 400123598
        }

        fetch('http://127.0.0.1:8000/items/40', {
            method: 'PUT',
            body: JSON.stringify(person)
        }).then(function(respones) {
            return respones.json();
        }).then(function(data) {
            console.log(data);
        })
    </script>

</body>

</html>

用浏览器打开上面的html文件,查看控制台即可:

在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐