代码之家  ›  专栏  ›  技术社区  ›  logisticregress

FastAPI未从Axios接收到简单的字符串数组

  •  0
  • logisticregress  · 技术社区  · 1 年前

    我被卡住了。我想我什么都试过了,但似乎都不起作用。 我在React中有一个简单的数组,看起来像这样:

    ["2023-06","2023-07","2023-08","2023-09","2023-10","2023-11","2023-12","2024-01","2024-02","2024-03","2024-04","2024-05"]

    其通过以下方式创建:

      let mydate = JSON.stringify(rowData.map(x => x.Date))
    

    我正在尝试使用以下方式将此数据发布到我的API服务:

    const savePlan = async () => {
      try {
        console.log(mydate)
        const response = await axios.post('/saveplan', {mydate},
        { headers: {
          'Content-Type': 'application/json'}}
        );
        console.log("data saved successfully!", response.data);
        } catch (error) {
        console.error('Error saving data', error);
        }
      };
    

    这是我的终点

    @app.post("/saveplan", tags=['save'], status_code=200)
    async def savePlan(items: Item):
        dates = items.dates
        return {"received": dates}
    

    Pydantic模型:

    class Item(BaseModel):
        dates: List[str]
    

    这是服务器响应:

    信息:127.0.0.1:59848-“POST/saveplan HTTP/1.1”422不可处理实体

    有人知道为什么我从这么简单的字符串数组中得到422吗?

    enter image description here

    1 回复  |  直到 1 年前
        1
  •  0
  •   Mario Vernari    1 年前

    我不知道 FastAPI ,但我想问题出在客户方面。

    我假设 Date 字段实际上是 string 而不是 日期 对象,则:

    let mydate = {
        dates: rowData.map(x => x.Date)
    };
    

    否则,我的建议是序列化为 ISO 。然而,这可能与 FastAPI ,我可能错了。

    let mydate = {
        dates: rowData.map(x => x.Date.toISOString())
    };
    

    此时:

    const savePlan = async () => {
      try {
        console.log(mydate)
        const response = await axios.post('/saveplan', mydate);
        console.log("data saved successfully!", response.data);
        } catch (error) {
        console.error('Error saving data', error);
        }
      };
    

    您甚至不需要在标头中指定内容类型,因为这是隐含的。