[英]How to add nested body to fetch()
如何將嵌套主體添加到fetch()
function?
我有這個身體:
{
"locations": [
{
"latLng": {
"lat": 123,
"lng": 123
}
},
{
"latLng": {
"lat": 123,
"lng": 123
}
}
]
}
我嘗試使用此代碼,但它返回我SyntaxError: Unexpected token o in JSON at position 1
:
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {
"locations": [
{
"latLng": {
"lat": 53.438679,
"lng": 14.520770
}
},
{
"latLng": {
"lat": 53.450439,
"lng": 14.536400
}
}
]
}
});
用於fetch
的 init object 的body
可以是以下之一: Blob
、 BufferSource
、 FormData
、 URLSearchParams
、 USVString
(字符串)或ReadableStream
object。 ( MDN |規范)
你沒有給它任何這些東西。 你給它一個普通的 object。 如果你想發送JSON ,你需要給它一個字符串:
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// −−−−−−−^^^^^^^^^^^^^^^
"locations": [
{
"latLng": {
"lat": 53.438679,
"lng": 14.520770
}
},
{
"latLng": {
"lat": 53.450439,
"lng": 14.536400
}
}
]
})
// −−−−−−^
});
您收到特定錯誤的原因是,由於您提供的內容不是它所期望的內容之一,因此fetch
正在將其轉換為字符串,就像您String(yourObject)
一樣。 在一個普通的 object 上,除非你已經做了一些事情來覆蓋它(你在你的例子中沒有這樣做),結果是"[object Object]"
,這是無效的 JSON 在object
之后的o
[
。
請記住:JSON 是用於數據交換的文本符號。 (更多在這里。)如果您正在處理 JavaScript 源代碼,而不是處理字符串,那么您就不是在處理 JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.