const data = { name, price, quantity, image, desc, sup_name, email }
fetch('https://gentle-plateau-90897.herokuapp.com/fruits', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body:(data)
})
.then(res => res.json())
.then(data => {
console.log(data)
window.alert('Item added')
e.target.reset()
})
我正在嘗試發布一種將資料發送到我的 MongoDB 資料庫的方法,但它拋出一個錯誤,提示“未捕獲(承諾中)SyntaxError: Unexpected token < in JSON at position 0”
uj5u.com熱心網友回復:
錯誤是由于res您從 API 獲得的轉換而出現的。這res是無法轉換為有效 JSON 的東西。
從錯誤來看,它似乎res可能是一個 HTML 字串并將其轉換為 JSON 總是會產生錯誤。要使用它,您應該innerHTML 在視圖中使用。
const data = { name, price, quantity, image, desc, sup_name, email }
fetch('https://gentle-plateau-90897.herokuapp.com/fruits', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body:(data)
})
// .then(res => res.json()) // remove this line for now
.then(data => {
/**
check here what type of data you are getting
is it valid JSON or not?
*/
console.log(data)
window.alert('Item added')
e.target.reset()
})
uj5u.com熱心網友回復:
Unexpected token < in JSON at position 0意味著您收到的是 HTML 回應而不是 json 回應,并且您正在嘗試將其轉換為 json。檢查開發工具中網路選項卡中的回應正文。它可能會回傳 HTML,因為您沒有包含Accept: application/json作為標題或發生了一些錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470066.html
標籤:javascript 节点.js json mongodb 表示
