首页 > 解决方案 > 如何正确使用 Body-parser 中间件

问题描述

我是 node.js 的新手,我无法正确启动 body-parser 中间件。

如教程所述,我尝试将 bodyParsers 实例化为 const,然后尝试在 app.use 中使用它。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

const users = [
  {name: 'Jones', email: 'jones@gmail.com'},
  {name: 'Henrique', email: 'henrique@hotmail.com'}
]

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/users', (req,res)=> {
  res.send(users);
})

app.post ('/users', (req,res)=>{
 console.log(req.body);
 res.end();
})

app.get('/', (req, res) => {
  res.send('Rota padrão');
  
  console.log();
  
});


// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}...`);
  
});

我收到了这个错误:

错误信息

标签: javascript

解决方案


推荐阅读