我遵循2-4年前创建的ReactJS教程。本教程将适应MVC模式。请求从server.js
开始,然后转到routes
文件。然后路由将其转发给controller
以给出相应的响应。
您可以查看下面的基本代码。
server.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}`)
})
/线路/auth.js
const express = require('express')
const router = express.Router()
// import controller
const {signup} = require('../controllers/auth')
router.post('/signup', signup);
module.exports = router; // {}
/控制器/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'
});
}
package.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"
}
}
然后使用邮递员使用POST
方法将数据发送到http://localhost:8000/api/signup
Content-Type: application/json
Accept: application/json
原始JSON
{
"name": "John",
"email": "johndoe@gmail.com",
"password": "mmmmm"
}
问题:我目前面临的问题是,当我通过邮差发送POST数据时,我在终端中看到req.body
为undefined
。请参见下面的终端输出。
$ 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进行解析,因为body-parser在express的4.16.0或更高版本中已被弃用。
你们知道我怎么解决这个问题吗?任何帮助都将非常感激。由于
中间件注册的顺序也很重要。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)