我正在嘗試通過 fetch 'POST' 請求將 html 表單資料發送到服務器,但在服務器端我得到了 Empty 請求正文。我已經嘗試過針對堆疊溢位提供的不同解決方案,但它們都沒有在我的最終作業。誰能幫我確定我哪里出錯了。
我的 html 檔案中有 ID 為“signup-form”的表單
客戶端 JavaScript 代碼如下所示:
const myForm = document.getElementById('signup-form')
myForm.addEventListener('submit', (e) => {
e.preventDefault()
const myForm = document.getElementById('signup-form')
const data = new FormData(myForm)
const option= {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body:JSON.stringify(data)
}
fetch('/login', option).then(
response => response.json()
).then(
data => console.log(data)
).catch(
error => console.log(error)
)
})
- 服務器端 express js 代碼如下所示
app.use(express.urlencoded({ extended: false}))
app.use(express.json())
app.post('/login', (req, res) => {
console.log('url is', req.url)
const info = req.body;
console.log('info is:', info)
res.status(201).json({ 'submitted': true })
})
app.listen(3000, () => {
console.log('listening on port 3000')
})
uj5u.com熱心網友回復:
FormData您不能發布應用程式/json,因為它不在元素支持的內容型別串列中form。
相反,寫類似
const data = {element1: "value", element2: "value2", ...};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411368.html
標籤:
下一篇:Express.jsER_TRUNCATED_WRONG_VALUE_FOR_FIELD:不正確的整數值:第1行的列'id'的''
