【问题标题】:How to change Content-Type: appication/x-www-form-urlencoded to application/json?如何将 Content-Type: application/x-www-form-urlencoded 更改为 application/json?
【发布时间】:2019-10-26 04:42:30
【问题描述】:

我正在尝试制作用户注册快递。我首先制作了后端,它似乎工作正常,因为我使用邮递员对其进行了验证。在邮递员中,我将 Content-Type 包含为 application/json,并将 json 数据包含在原始数据选项卡中。但是,在制作表单(姓名、电子邮件、密码)时,我无法将这个后端实现到前端。我收到了错误,包括姓名、电子邮件和密码,即使我这样做了。我试图 console.log 的 req.body 并得到空数组。但是,在 Chrome 的网络选项卡中,姓名、电子邮件和密码都包含在 Form-Data 中。我不认为问题出在正文解析器上,因为邮递员没有任何问题。在network选项卡中,我看到req的Content-Type是Content-Type: application/x-www-form-urlencoded而不是application/json,我认为这可能是错误的原因。

server.js

app.use(express.json({ extended: false }));
app.get('/register', (req, res) => res.render('register'));
app.use('/api/users', require('./routes/api/users'));

api/users.js

// @ route    POST api/users
// @desc      Register User
// @access    Public
router.post(
  '/',
  [
    check('name', 'Name is required')
      .not()
      .isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check(
      'password',
      ' Please enter a password with 6 or more characters'
    ).isLength({ min: 6 })
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log(req.body);
      return res.status(400).json({
        errors: errors.array()
      });
    }
    const { name, email, password } = req.body;
.
.
.

register.handlebars

  <form class="form" action="/api/users" method="post">
                <div class="form-group">
                    <input name="name" type="text" placeholder="Name" requried>
                </div>

                <div class="form-group">
                    <input name="email" type="email" placeholder="E-mail">
                </div>

                <div class="form-group">
                    <input name="password" type="text" placeholder="Password" minlength="6">
                </div>
                <input type="submit" value="Create account" class="button green-button" />
            </form>

【问题讨论】:

  • 尽管它可以在 Postman 中工作,但我仍然不确定您是否正确使用了正文解析器。尝试删除 app.use(express.json({ extended: false })); 并添加以下内容而不是 const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));。对不起那个单行字,但我不确定这是否可以被认为是一个答案,所以我不能在这里格式化代码。
  • 哦,成功了!你能解释一下为什么吗?来自邮递员的请求和来自浏览器的请求有什么区别?

标签: node.js express


【解决方案1】:

express.json()Content-Type: application/json 数据的解析器。您在代码中使用它,这就是它在 Postman 中工作的原因。为了解析编码为application/x-www-form-urlencoded 的数据,您只需添加另一个解析器,在本例中为express.urlencoded()。此外,extended 选项被urlencoded() 接受,而不是json()

app.use(express.json()) // parses application/json
app.use(express.urlencoded({ extended: true })) // parses application/x-www-form-urlencoded

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2019-05-24
    • 2018-12-27
    相关资源
    最近更新 更多