從 JavaScript 發送 JSON 資料到 FastAPI 如何處理錯誤?

Mary-Kate Olsen
發布: 2024-11-13 16:53:03
原創
841 人瀏覽過

How to Handle Errors When Sending JSON Data from JavaScript to FastAPI?

Error Handling in Posting JSON Data from JavaScript to FastAPI

To send data from a JavaScript frontend to a FastAPI backend, you must ensure the data is passed in the correct format and to the appropriate endpoint. If you encounter a 422 Unprocessable Entity error, it's likely due to incorrect data formatting.

Query Parameters vs. JSON Parameters

By default, FastAPI interprets function parameters not included in the path as query parameters. However, for JSON data, you need to specify it explicitly using one of the following methods:

1. Pydantic Model:

Define a Pydantic model to represent the JSON data structure:

from pydantic import BaseModel

class Item(BaseModel):
    eth_addr: str

@app.post('/ethAddress')
def add_eth_addr(item: Item):
    return item
登入後複製

2. Body Type:

Use the Body type to specify that the parameter should be parsed from the request body:

from fastapi import Body

@app.post('/ethAddress')
def add_eth_addr(eth_addr: str = Body()):
    return {'eth_addr': eth_addr}
登入後複製

3. Body Embed:

For a single body parameter, you can use the embed=True argument to automatically parse the data from the request body:

from fastapi import Body

@app.post('/ethAddress')
def add_eth_addr(eth_addr: str = Body(embed=True)):
    return {'eth_addr': eth_addr}
登入後複製

JavaScript Fetch API

When using the Fetch API in JavaScript to send JSON data, you must set the Content-Type header to application/json and specify the data in the body field:

fetch("http://localhost:8000/ethAddress", {
  method: "POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "eth_addr": "some address"
  }),
});
登入後複製

Additional Resources

For more information and detailed examples, refer to the following documentation and resources:

  • [FastAPI JSON Request and Response](https://fastapi.tiangolo.com/tutorial/body/)
  • [Sending JSON data with POST requests in JavaScript](https://stackoverflow.com/questions/44832885/sending-json-data-with-post-requests-in-javascript)
  • [POST request with JSON content in JavaScript using Fetch API](https://stackoverflow.com/questions/55749929/post-request-with-json-content-in-javascript-using-fetch-api)

以上是從 JavaScript 發送 JSON 資料到 FastAPI 如何處理錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板