使用fetch调用fastapi接口(post)的实例

前端代码

//定义函数
async function sendRequest(data) {
    let myurl="http://127.0.0.1:8848/get_student_info"
    const response = await fetch(myurl, {
      method: 'POST',
      mode: 'cors',  // 执行跨域请求
      headers: {
        'Content-Type': 'application/json',         
      },
      body: JSON.stringify({         
        "name": "山南",
        "gender": "男",    
      })
    });  
    let res = '';
    let str;
     // 等待 Promise 对象被解决(resolved)
    const json_res = await response.json();
    str=json_res.age
    addResponseMessage(String(str)); 
    return str;
  }
  let data;
  data = { "apiKey": ""};
 // 将data传入sendRequest然后处理该函数的返回值res
    sendRequest(data).then((res) => {     
      // 重新绑定键盘事件
      chatInput.on("keydown",handleEnter); 
      // 判断是否是回复正确信息
      if(resFlag){
        messages.push({"role": "assistant", "content": res});         
    });

python fastapi后端

from typing import Union
from fastapi import FastAPI
from uvicorn import run #直接在py文件中启动webapi服务
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware #解决跨域问题https://blog.csdn.net/Tong_yanpeng/article/details/122893166

app = FastAPI()

# 不知为何如果添加了准确的ip和端口号,则仍然存在跨域问题,因此,允许所有来源的请求。
origins = ["*"]   
#  配置允许域名列表、允许方法、请求头、cookie等
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)
 #   声明参数类 fastapi要对前端传过来的参数进行校验,所以要定义对应的类
class Student(BaseModel):
    name: str
    gender: str
@app.post("/get_student_info")
async def get_student_info(request_data: Student):
    name = request_data.name+"_ok"
    gender =  request_data.gender+"_ok"
    age=18
    res = {'name':name,'gender':gender,'age':18,'status':200}
    return res  # 返回一个json

if __name__ == '__main__':
    print("start")
    run(app, host="127.0.0.1", port=8848)  # http://127.0.0.1:8848
    print("end")

你可能感兴趣的:(fastapi,python)