当我使用swagger UI点击这个API时,这段代码工作得很好.但当它被显示状态代码422 unprocessable entity的Reaction前端击中时,无法执行.下面是我的Fastapi端点-


@post.post('/post')
async def create_post(post_text: str, image: bytes = File(None), token: str = Depends(oauth2_scheme), db: Session = Depends(database.get_db)):
    user_info = await services.get_user_info(token)
    username = user_info["username"]
    print(username)
    image_url = None
    if image:
        # Generate a unique filename for the image
        image_filename = f"{username}_{uuid.uuid4().hex}.jpg"
        # print(image_filename)

        # Save the image to bytes and send to MinIO bucket
        # image_bytes = await image.read()
        image_bytes = base64.b64decode(image.split(",")[1])

        minio_client.put_object(
            "minilinkedindistributed",
            image_filename,
            io.BytesIO(image_bytes),  
            length=len(image_bytes),
            content_type="image/jpeg"
        )

        # Construct the image URL based on MinIO server URL and bucket name
        image_url = f"http://127.0.0.1:9000/minilinkedindistributed/{image_filename}"
        print(image_url)
    elif image is None or image.filename == '':
        raise HTTPException(status_code=400, detail='Invalid or empty image file')
    # Create the post
    new_post = services.make_post(db, username, post_text, image_url)

    headers = {"Authorization": f"Bearer {token}"}

    # Get all users (except the one who posted)
    async with httpx.AsyncClient() as client:
        response = await client.get("http://127.0.0.1:8000/api/v1/all_users_except_poster", headers=headers)

    if response.status_code == 200:
        all_users_except_poster = response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail="Failed to fetch users from user service")

    # Create a notification for each user
    for user_to_notify in all_users_except_poster:
        notification_data = {
            'notification_text': f"{username} made a new post...",
            'pid' : new_post.id,
            'username' : user_to_notify["username"],
            'notification_datetime' : datetime.utcnow().isoformat(),
            'is_read' : False
        }

        
        async with httpx.AsyncClient() as client:
            response = await client.post("http://127.0.0.1:8002/api/v1/notification", json=notification_data, headers=headers)

        if response.status_code != 200:
            raise HTTPException(status_code=response.status_code, detail="Failed to send notification")
    

    return{"message" : new_post}

下面是我的Reaction组件-



const HomePage = () => {
  const [posts, setPosts] = useState([]);
  const [loggedIn, setLoggedIn] = useState(false);
  const [postText, setPostText] = useState('');
  const [selectedImage, setSelectedImage] = useState(null);
  const [notifications, setNotifications] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    const access_token = localStorage.getItem('access_token');
    if (access_token) {
      setLoggedIn(true);
      fetchPosts(access_token);
    }
  }, []);


  const handlePostTextChange = (event) => {
    setPostText(event.target.value);
  };

  const handleImageChange = (event) => {
    setSelectedImage(event.target.files[0]);
  };

  const handleSubmitPost = async () => {
    const formData = new FormData();
    formData.append('post_text', postText); // Make sure 'postText' holds the user's post text
    if (selectedImage) {
      formData.append('image', selectedImage, selectedImage.name); // Make sure 'selectedImage' holds the user's selected image
    }else console.log('Invalid or empty image file');
    console.log("Post Text:", postText);
    console.log("Selected Image:", selectedImage);
    console.log('FormData:', formData);

    const access_token = localStorage.getItem('access_token');
  
    // Make a POST request to create a new post
    try {
      const response = await axios.post(`${API_BASE_URL}/post`, formData, {
        headers: {
          Authorization: `Bearer ${access_token}`,
          'Content-Type': 'multipart/form-data', // Set the correct content type for the form data
        },
      });

      // Refresh the posts after successful submission
      fetchPosts(access_token);
      
    } catch (error) {
      console.error('Error submitting post:', error.response);
    }

  };

被困在这里很久了, 任何解决方案都会有所帮助. 谢谢

我试着在谷歌上搜索,也看到了一些堆栈溢出的解决方案,但我try 了所有的解决方案,仍然不起作用.即使是喋喋不休也没能解决这个问题.需要尽快解决方案

推荐答案

通常,422 (unprocessable entity) response includes an error message表示您的请求中缺少或不匹配预期格式的确切部分/值.因此,请务必查看这一点,并将其包括在您的问题中.

在您的例子中,您似乎在前端使用axiosForm数据发布到FastAPI后端.但是,在终结点中定义post_text参数的方式应该是query参数,而不是Form参数.

100 expected as query parameter

@app.post('/create')
async def create_post(post_text: str):
    pass

如第this answer条、第here条和第here条所述(有关更多详细信息和示例,请参阅这些帖子):

当您声明其他不属于 路径参数,它们被automatically解释为"查询" 参数.

因此,如果您希望post_text作为Form参数,则应按如下方式声明它:

一百零二

from fastapi import Form

@app.post('/create')
async def create_post(post_text: str = Form(...)):
    pass

相关解答展示了如何在前端通过axiosfetch请求将File/Form数据发布到FastAPI后台,可以在hereherehereherehere找到相关答案.

Python相关问答推荐

替换为Pandas

使用子字符串动态更新Python DataFrame中的列

在后台运行的Python函数

如何在Python中按组应用简单的线性回归?

避免循环的最佳方法

用Python获取HTML Span类中的数据

Tkinter滑动条标签.我不确定如何删除滑动块标签或更改其文本

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

使用多个性能指标执行循环特征消除

由于瓶颈,Python代码执行太慢-寻求性能优化

线性模型PanelOLS和statmodels OLS之间的区别

rame中不兼容的d类型

将输入管道传输到正在运行的Python脚本中

无法通过python-jira访问jira工作日志(log)中的 comments

在Python中管理打开对话框

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

转换为浮点,pandas字符串列,混合千和十进制分隔符

不允许访问非IPM文件夹

Flash只从html表单中获取一个值