python - POST http://127.0.0.1:8000/pruebi/prueba 422(无法处理的实体)
问题描述
尝试将文本从输入上传到数据库时,我在代码中遇到错误:
POST http://127.0.0.1:8000/pruebi/prueba 422 (Unprocessable Entity)"
我正在使用 fastapi、nextjs 和 python。
我的代码分为我在 nextjs 中完成的前端,其中找到了文本输入以及尝试发送此文本的 fetch。一个 fastapi 路由程序,允许您绑定此前端并进行模型调用。最后是模型,这是一个 python 程序,用于上传传递给 mongodb 的数据。在这里我留下我的代码,希望你能帮助我,非常感谢。
Nextjs 前端:
import { useForm } from 'react-hook-form';
import axios from 'axios';
import { useRouter } from 'next/router';
export default function Home() {
const { register, handleSubmit, errors, reset } = useForm();
const router = useRouter();
async function onSubmitForm(name) {
fetch('http://127.0.0.1:8000/pruebi/prueba', {
method: 'POST',
body: JSON.stringify(name),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
return (
<div>
<form onSubmit={handleSubmit(onSubmitForm)}>
<input {...register("name")} type="text" name="name" required/>
<button type="submit">Submit</button>
</form>
</div>
);
}
路线:
from fastapi import APIRouter
from starlette.responses import RedirectResponse
from model.insert_date import MongoDB
router = APIRouter()
@router.post("pruebi/prueba", name="Insert the date in mongo", tags=["consultas"])
async def insertDate(start_date):
db = MongoDB.__init__(dBName="HAR", collectionName="date")
MongoDB.InsertDate(db,start_date)
response = RedirectResponse(url='http://localhost:3000/paginaGrafica')
return response
我的模型:
try:
import pymongo
from pymongo import MongoClient
import pandas as pd
import json
from datetime import date
except Exception as e:
print("Some Modules are Missing ")
class MongoDB(object):
def __init__(dBName=None, collectionName=None):
client = MongoClient("localhost", 27017, maxPoolSize=50)
DB = client[dBName]
collection = DB[collectionName]
return(collection)
def InsertDate(collection,start_date):
data = [{'start_date': start_date}]
collection.insert_many(data, ordered=False)
print("All the Data has been Exported to Mongo DB Server .... ")
解决方案
推荐阅读
- sql - 基于日历表的以秒为单位的营业时间功能
- python - 如何在 QWidget 上添加背景图像并在其上添加位置 QLineedit?
- bash - 如何根据列拆分文件然后将该列放入 awk 或 bash
- android - 这些在 UI 线程上运行代码的方法有什么区别?
- javascript - Mongoose 在 [Mixed]-Arrays 的查询中自动插入“$in”
- angular - “对象”类型不存在属性“方向”
- javascript - 如何将 Post 请求发送到我做出反应的 php 文件?
- odoo - Odoo:是否可以为多个联系人使用同一个银行帐户?
- reactjs - 在 apollo 客户端 GraphQL React 应用中添加对特定路由的订阅
- sql - 如何从 SQL Server 上的 XML 列中选择数据?