javascript 如何使用express js内置的body解析器?

lsmd5eda  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(101)

我正在学习一个2-4年前创建的ReactJS教程。该教程正在适应MVC模式。请求从server.js开始,然后转到routes文件。然后路由将其转发到controller以相应地给予任何响应。
您可以在下面查看基本代码。

服务器.js

const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
require('dotenv').config()

const app = express()

// connect to db
mongoose
    // connection code
  })
  .then(() => console.log('DB connected'))
  .catch(err => console.log('DB CONNECTION ERROR: ', err))

// import routes
const authRoutes = require('./routes/auth')

// middleware
app.use('/api', authRoutes)

// app midllewares
app.use(morgan('dev'))
app.use(express.json()) // body-parser is now deprecated as of Express 4.16+
app.use(express.urlencoded({ extended: true }))

const port = process.env.PORT || 8000
app.listen(port, () => {
  console.log(`API is running on port ${port} - ${process.env.NODE_ENV}`)
})

/routes/auth.js

const express = require('express')
const router = express.Router()

// import controller
const {signup} = require('../controllers/auth')

router.post('/signup', signup);

module.exports = router; // {}

/controllers/auth.js

const express = require('express')

exports.signup = (req, res) => {
  console.log('REQ BODY ON SIGNUP', req.body); // shows the posted data on terminal
  res.json({
    data: 'you hit signup endpoint'
  });

}

包.json

{
  "dependencies": {
    "@sendgrid/mail": "^7.7.0",
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-jwt": "^8.4.1",
    "express-validator": "^6.15.0",
    "google-auth-library": "^8.7.0",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^7.0.3",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.22"
  }
}

然后使用postman使用POST方法将数据发送到http://localhost:8000/api/signup

标题

Content-Type: application/json
Accept: application/json

原始JSON

{
    "name": "John",
    "email": "johndoe@gmail.com",
    "password": "mmmmm"
}

**问题:**我目前遇到的问题是,我通过postman发送POST数据时,在终端看到的是req.bodyundefined,请看下面的终端输出。

$ npm start

> mern-auth-server@1.0.0 start
> nodemon server.js

[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
API is running on port 8000 - development
DB connected
REQ BODY ON SIGNUP undefined

我使用express进行解析,因为自express 4.16.0或更高版本以来,body-parser已被弃用。
你们知道我该怎么解决这个问题吗?任何帮助都将不胜感激。谢谢

rwqw0loc

rwqw0loc1#

中间件注册的顺序也很重要。JSON请求主体解析应该在命中路由之前进行,因为路由需要解析的主体。因此需要在附加路由之前移动解析中间件。

// import routes
const authRoutes = require('./routes/auth')

// app midllewares
app.use(morgan('dev'))
app.use(express.json()) // body-parser is now deprecated as of Express 4.16+
app.use(express.urlencoded({ extended: true }))

// middleware
app.use('/api', authRoutes)

相关问题