【问题标题】:express nodejs POST request form input methodexpress nodejs POST请求表单输入法
【发布时间】:2020-08-24 20:14:32
【问题描述】:

谁能帮我理解为什么我得到一个空的身体?

文档上说 express.json() 使用 body-parser,所以它与我使用 express.json() 或 bodyParser() 相同?

关于文档还说我可以通过 json 对象选项的选项设置来提供标头的类型...我认为它是这样的:

app.use(express.json({ type: 'application/json' }))

我的标题内容类型说:'content-type':'application/x-www-form-urlencoded' 正如文档所说,默认值为“application/json”。

我需要以 json 格式取回表单值,以便我可以保存数据库和其他内容。

我参考的文档:http://expressjs.com/en/api.html#express.json

【问题讨论】:

  • express.json() 默认无法以您想要的方式解析表单字段。您需要将类型更改为 'application/x-www-form-urlencoded'
  • 好的,所以如果我将 app.use(express.json()) 设置为中间件并将其配置为接受 x-www-form-urlencoded,它将在路由上工作,但如果在另一条路线上,如 app.post('/users/avatar'...) 我想要一张图片,或者在 app.get('/users/me'...) 我想要一个 json ......我该如何配置这些类型的东西? @Cehhiro 感谢您显示链接,但我认为它有点不同。
  • 我试过这个: app.use(express.urlencoded({ extended: true })) app.use(express.json({ type: 'application/x-www-form-urlencoded' } )) 仍然得到空对象。当我使用邮递员时,它确实有效。

标签: javascript node.js json express


【解决方案1】:

好吧,我想通了。

整个问题在于 html 输入。与解析器配置无关。

问题在于,例如,当您通过邮递员发送某些东西时, 如果你想发送 application/x-www-form-urlencoded 类型,邮递员会给你一个接口让你设置一个键值对。如果您使用原始 json 与我认为的“application/json”相同,您将必须设置一个有效的 json,并带有键值对。

在邮递员上,如果您在没有提供值的键的情况下发送,则 req.body 将导致为空,如文档中所说的那样

"一个包含解析数据的新主体对象被填充到 中间件之后的请求对象(即req.body),或者一个空的 object ({}) 如果没有要解析的主体,则 Content-Type 不是 匹配,或发生错误。”

我从来不明白 html 输入和东西上的“名称”属性的原因。好吧,我谦虚地认为这就是价值(我还没有搜索过)。

解决方案是在输入上设置名称属性 =>

body 的响应是 => name:'...输入的任何内容...'

代码:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <form action="/" , method="POST">
            <!-- <input type="text" id="name" name="name" placeholder="name" required> -->
            <input type="text" name="name"> // name attribute is the key "name" for your input.
            <input type="text" name="age"> // name attribute is the key "age" for your attribute.
            <input type="submit">
        </form>
    </body>

</html>

javascript:

const express = require('express')
const path = require('path')

const app = express()

app.use(express.urlencoded({ extended: true }))
app.use(express.json())


app.get('/', (req, res) => {
    res.sendFile('index.html', { root: path.join(__dirname) })
})

app.post('/', (req, res) => {
    console.log(req.body) // the result is the input value.
})

app.listen(3000, () => {
    console.log('working')
})

【讨论】:

    猜你喜欢
    • 2020-12-05
    • 2019-06-26
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2016-04-27
    • 2019-07-21
    相关资源
    最近更新 更多