html 向FastAPI上托管的本地服务器发送POST请求

zzoitvuj  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(407)

我有一个运行在FastAPI上的本地服务器,使用了以下Python代码:

from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "*"
    '''
    "http://localhost:8000/add_points/",
    "http://localhost:8000/check_points/",
    "http://localhost:8000/check_item_points/",
    "http://localhost:8000/redeem_points/"
    '''
]

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

users = {"matt": 0}
items = {"ticket": 7}

class User(BaseModel):
    name: str
    points: float
    item: str

class AddTransaction(BaseModel):
    name: str
    points: float

class UserPoints(BaseModel):  # anything that extnds this base model is a pyantic model
    name: str
    points: float

class Item(BaseModel):
    name: str
    points: float

# -----Post Requests-----
@app.post("/add_points/")
def add_points(add_transaction: AddTransaction):
    global users
    user_id = add_transaction.name
    points = add_transaction.points
    users[user_id] = users.get(user_id, 0) + points
    return users[user_id]

@app.post("/check_points/")
def check_points(user_points: UserPoints):
    global users
    user_id = user_points.name
    points = user_points.points
    return users[user_id], points

@app.post("/check_item_points/")
def check_item_points(item: Item):
    global items
    item_id = item.name
    points = item.points
    return item[item_id], points

@app.post("/redeem_points/")  # user spends points (they lose points) gain an item
def redeem_points(add_transaction: AddTransaction, user_points: UserPoints, item: Item, user: User):
    global users
    global items
    user_id = add_transaction.name
    user_points = user_points.points
    item_points = item.points
    item_pre = item.name
    item_post = user.item
    if user_points >= item_points:
        user_points == user_points - item_points
        item_post == item_pre
        return users[user_id], users[user_points], users[item_post]
    else:
        return "insufficient funds"

# -----Get Requests-----
@app.get("/")
def read_root():
    return {"Hello": "World"}

# -----Put Requests-----
""""
@app.put("/items/{item_id}")
def update_item(item_id: int, item:Item):
    return {"item_name": item.name, "item_id": item_id}
"""

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

我还有一个HTML脚本,它在单击一个按钮时向http://localhost:8000/add_points/发送一个post请求。

<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
<br><br><br><span style="text-align: center;"><button id="send">Send Request</button></span>
</body>

<script>
$("#send").on("click", evt => {
    $.post("http://localhost:8000/add_points/",
  {
    name: "string",
    points: 5.0
  },
  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
</script>

</html>

但是,当我尝试发送POST请求时,我在PyCharm中收到以下错误:
HTTP/1.1”400错误的请求
信息:127.0.0.1:49413-“POST /添加点/ HTTP/1.1”422无法处理的实体
我知道这些错误中至少有一个是由CORS政策限制引起的,但是,这个项目是针对移动的电话用户的,他们必须安装任何浏览器扩展来覆盖政策。任何关于如何修复这些错误的建议将不胜感激!
编辑更新:

const url = new URL('localhost:8000/add_points/');
$("#send").on("click", evt => { fetch(url, 
      { 
        method: 'POST', 
       headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}, 
          body: JSON.stringify({"name":"John", "points":50.0}) 
      }).then().catch((error) => { console.log(error.message); }); });

我仍然收到400 Bad Request错误。

46scxncf

46scxncf1#

如果您从Jinja2 templateHTMLResponse访问fronted(从应用程序侦听的port以及您在CORSMiddleware中定义的origins可以看出,似乎就是这种情况),则不需要为应用程序启用CORS。两个对象具有相同的原点protocoldomainport全部匹配时。
请注意,localhost127.0.0.1被认为是不同的源。因此,如果您从浏览器访问http://127.0.0.1:8000/的前端(通过在地址栏中输入URL),那么您的异步JS请求(例如使用fetch)应该使用该域;例如:

fetch('http://127.0.0.1:8000/add',...

不是

fetch('http://localhost:8000/add',...

您可以始终使用相对路径来处理您的fetch请求(如下所示),因此,无论您使用哪个域名(localhost127.0.0.1)从浏览器访问前端,您的应用都可以正常工作。

工作示例:

请参阅相关答案hereherehere

应用程序.py

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class Item(BaseModel):
    name: str
    points: float

@app.post("/add")
def add_points(item: Item):
    return item
    
@app.get("/")
def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

模板/索引.html

<!DOCTYPE html>
<html>
   <body>
      <input type="button" value="Submit" onclick="submit()">
      <div id="responseArea"></div>
      <script>
         function submit() {
            fetch('/add', {
                 method: 'POST',
                 headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                 },
                 body: JSON.stringify({'name': 'John', 'points': 50.0})
              })
              .then(resp => resp.text()) // or, resp.json(), etc.
              .then(data => {
                 document.getElementById("responseArea").innerHTML = data;
              })
              .catch(error => {
                 console.error(error);
              });
         }
      </script>
   </body>
</html>

相关问题