繁体   English   中英

express nodejs POST 请求表单输入法

[英]express nodejs POST request form input method

在此处输入图片说明

有人能帮我理解为什么我的身体是空的吗?

文档上说 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

好吧,我想通了。

整个问题出在 html 输入上。 不是解析器配置。

问题是,例如,当您通过邮递员发送某些内容时,如果您想发送 application/x-www-form-urlencoded 类型,邮递员将为您提供一个界面来设置键值对。 如果您使用原始 json 与“应用程序/json”相同,我认为您将必须设置一个有效的 json,并带有键值对。

在邮递员上,如果您在不提供值的键的情况下发送任何一个,则 req.body 将导致为空,如 express 在文档中所述

“在中间件之后的请求对象上填充包含解析数据的新正文对象(即 req.body),或者如果没有正文要解析,则内容类型不匹配,则为空对象 ({}),或发生错误。”

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

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

身体的响应是 => 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')
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM