我正在嘗試對私有 API(托管 Itop)進行 API 請求,檔案中有一個使用 JQuery Ajax 的示例,但我使用 fetch 進行了所有其他呼叫,我也想做這個,但我沒有得到正確的反應。
fetch 方法回傳一個代碼 200,但使用 HTML 而不是 JSON(與 jQuery AJAX JSON 的內容完全不同)。
這是2個功能:
// Code made by myself - don't get the right response
fetch(url, {
method: "POST",
headers: {
"accept": "application/json",
},
mode: "cors",
accept: "application/json, text/javascript, *!/!*; q=0.01",
body: JSON.stringify({
auth_user: user,
auth_pwd: password,
json_data: JSON.stringify({
"operation": "list_operations",
})
})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
// Code from the doc example - working
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: {
auth_user: user,
auth_pwd: password,
json_data: JSON.stringify({
"operation": "list_operations"
})
},
crossDomain: 'true'
})
.then(
function(data, textStatus, jqXHR) {
console.log(data);
console.log(textStatus);
console.log(jqXHR);
},
function(jqXHR, textStatus, errorThrown) {
console.debug(jqXHR);
console.log("ERROR !!\n"
"status: " textStatus " (" jqXHR.status ")\n"
"error: " errorThrown);
}
);
uj5u.com熱心網友回復:
在 jQuery.ajax 中,當你傳遞data
一個物件時:
- 它將被編碼為
application/x-www-form-urlencoded
資料 - jQuery 將包含一個
Content-Type: application/x-www-form-urlencoded
標題
在 fetch 中,您傳遞body
的是 JSON 字串,并且 fetch 將包含一個Content-Type: text/plain
標頭。
所以:
- 您傳遞的資料編碼錯誤
- 您傳遞的 Content-Type 與服務器期望的或您的資料實際不匹配
傳遞fetch
一個URLSearchParams
物件。
這將使用正確的格式進行編碼,并fetch
從中推斷出正確的內容型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475790.html
標籤:javascript jQuery 阿贾克斯 拿来