【发布时间】:2022-01-12 16:45:01
【问题描述】:
我正在尝试通过 fetch 'POST' 请求将 html 表单数据发送到服务器,但在服务器端我得到了 Empty request body。我已经尝试过针对堆栈溢出提供的不同解决方案,但它们都没有在我的最终工作。谁能帮我确定我哪里出错了。
-
我的 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')
})
【问题讨论】:
标签: javascript node.js express fetch-api