【问题标题】:Empty body at server side when using fetch使用 fetch 时服务器端的空正文
【发布时间】:2022-01-12 16:45:01
【问题描述】:

我正在尝试通过 fetch 'POST' 请求将 html 表单数据发送到服务器,但在服务器端我得到了 Empty request body。我已经尝试过针对堆栈溢出提供的不同解决方案,但它们都没有在我的最终工作。谁能帮我确定我哪里出错了。

  1. 我的 html 文件中有 id 为“signup-form”的表单

  2. 客户端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)
    )
})
  1. 服务器端 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


【解决方案1】:

使用FormData,您不能发布应用程序/json,因为这不在form 元素支持的list of content types 上。

相反,写一些类似的东西

const data = {element1: "value", element2: "value2", ...};

【讨论】:

  • 谢谢,问题解决了
猜你喜欢
  • 2020-02-15
  • 1970-01-01
  • 2022-06-14
  • 2018-11-29
  • 2021-10-31
  • 2023-03-25
  • 2021-01-15
  • 2022-01-19
  • 2014-11-01
相关资源
最近更新 更多