我想用jQuery提供的 AJAX 在javascript中调用API,但是我收到了一个无法处理的实体错误(fastapi服务器发出的pydantic错误响应)。奇怪的是curl命令确实有效。我不清楚为什么我的服务器可以区分错误的ajax调用和成功的curl调用。
curl -X 'POST' \
'http://127.0.0.1:8010/api/update' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"gsid":"634ad79ee29c42396b0d4055","ticker":"SPX230317C04200000","security_type":5,"security_subtype":2005,"option_flavor":2,"underlying":{"gsid":"634ad6d1d89536dac325f871","ticker":"SPX"},"denominated_ccy":{"gsid":"634ad6d1d89536dac325f86e","ticker":"USD"},"expiry_date":"2023-03-17","strike":4200,"option_exercise":1,"expiry_series_type":20,"expiry_time_of_day":1,"settlement_type":1,"primary_exchange":"CBO","multiplier":100,"issuer":0,"description":0,"website":0,"as_of_date":"1970-01-01T00:00-05:00","expiry_datetime":"1969-12-31T19:00-05:00","identifiers":[{"id_type":2,"value":""},{"id_type":3,"value":""},{"id_type":4,"value":""},{"id_type":5,"value":""}]}'
我的API正确地响应此调用,并给出以下200成功响应:
{
"success": true,
"created_security": false,
"gsid": "634ad79ee29c42396b0d4055",
"available_versions": [
"1970-01-01T00:00:00-05:00"
],
"message": "success"
}
使用jQuery进行 AJAX 调用
data = {"gsid":"634ad79ee29c42396b0d4055","ticker":"SPX230317C04200000","security_type":5,"security_subtype":2005,"option_flavor":2,"underlying":{"gsid":"634ad6d1d89536dac325f871","ticker":"SPX"},"denominated_ccy":{"gsid":"634ad6d1d89536dac325f86e","ticker":"USD"},"expiry_date":"2023-03-17","strike":4200,"option_exercise":1,"expiry_series_type":20,"expiry_time_of_day":1,"settlement_type":1,"primary_exchange":"CBO","multiplier":100,"issuer":0,"description":0,"website":0,"as_of_date":"1970-01-01T00:00-05:00","expiry_datetime":"1969-12-31T19:00-05:00","identifiers":[{"id_type":2,"value":""},{"id_type":3,"value":""},{"id_type":4,"value":""},{"id_type":5,"value":""}]};
payload = JSON.stringify(data);
$.ajax({
url: 'http://127.0.0.1:8010/api/update',
type : "POST",
dataType: 'json',
processData: false,
success: function(data){
console.log('success: '+JSON.stringify(data));
},
error: function(data){
console.log('error: '+JSON.stringify(data));
},
data : payload,
});
这里我从我的服务器得到了以下422不可处理的实体响应:
{"readyState":4,"responseText":"{\"status_code\":10422,\"message\":\"4 validation errors for Request body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict)\",\"data\":null}","responseJSON":{"status_code":10422,"message":"4 validation errors for Request body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict) body value is not a valid dict (type=type_error.dict)","data":null},"status":422,"statusText":"Unprocessable Entity"}
2条答案
按热度按时间xa9qqrwz1#
编辑将以下内容添加到 AJAX 调用中:
@addjunior提出的答案
ukqbszuj2#
就我个人而言,我***永远***不会使用jQuery做任何事情。
下面是在JavaScript中的实现方式。