首页 > 解决方案 > 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 .... ")

标签: pythonmongodbnext.jsfastapi

解决方案


推荐阅读