我使用快速 api 在 python 上創建了一個 REST 服務,我需要使用 js 呼叫這些 api。這是我的python api:
class FieldUpdate(BaseModel):
item_id: Optional[int] = None
field_name: Optional[str] = None
field_value: Optional[str] = None
@router.patch("/update/item", response_model=FieldUpdate)
def update_item(body: FieldUpdate):
item_id = body.item_id
field_name = body.field_name
field_value = body.field_value
ctx_sle = get my current contenxt
status = execute method after contenxt initialization (it has nothing to do with running the API)
return status
在我的 js 腳本中,我使用 fetch 嘗試這個請求
class FieldUpdate {
constructor(item_id, field_name, field_value) {
this.item_id = item_id;
this.field_name = field_name;
this.field_value = field_value;
}
}
async function update_field_from_cell(field) {
const url = "http://127.0.0.1:8080/scriptlab/update/item";
try {
await fetch(url, {
method: "PATCH",
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: field
})
.then(function(response) {
console.log(response.status);
console.log(response.text());
});
} catch (error) {
console.log(error);
}
}
但是每次我運行這個請求時,它都會回傳 422 Unprocessable Entity 錯誤。你有什么技巧可以解決這個問題嗎?
uj5u.com熱心網友回復:
如前所述, 當接收到的有效負載與預期不匹配時,將引發422 Unprocessable Entity錯誤。您的腳本發送一個 JS 物件,但應該發送一個 JSON 字串,如下面的代碼所示。此外,請確保在您的請求中使用正確的 url(因為我注意到您使用的 URL 與 API 中的任何端點都不匹配)。請記住將 body 屬性也更改body: json_data為。
async function update_field_from_cell(field) {
var obj = {"item_id": field.item_id, "field_name": field.field_name, "field_value": field.field_value};
json_data = JSON.stringify(obj);
const url = "http://127.0.0.1:8000/update/item";
try {
await fetch(url, {
method: "PATCH",
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: json_data
})
.then(function(response) {
console.log(response.status);
console.log(response.text());
});
} catch (error) {
console.log(error);
}
}
uj5u.com熱心網友回復:
如果請求負載與您的 API 接受的實際負載不匹配,則會拋出錯誤代碼 422。
您使用的 Pydantic 模型僅驗證和接受匹配的請求負載。
可在此處使用的示例有效負載:
1)
{
"item_id":1, #integer
"field_name": "some_name", #string
"field_value": "some_value" #string
}
- 任何值都可以為“null”。因為您提到所有欄位都是可選的:
{
"item_id":null, #integer
"field_name": "some_name", #string
"field_value": null #string
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409931.html
標籤:
