我是ExpressJ的新手,我想执行POST请求,但无法使Body Parser正常工作
const express = require("express");
const path = require("path");
const config = require("./config");
// const logger = require("./middleware/logger")
// init express
const app = express();
// set 'public' as STATIC directory
app.use(express.static(path.join(__dirname, "public")));
// init middleware
// app.use(logger);
// setup parent router for api/people
app.use('/api/people', require("./routes/api/members"));
// adding body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// set PORT listen
app.listen(config.PORT, () =>
console.log(
`damiisdandy's server running on port ${config.PORT}... at ${config.time}`
)
);
这里是路由文件
const express = require('express')
const uuid = require('uuid')
const config = require('../../config')
const router = express.Router();
router.post("/", (req, res) => {
res.send(req.body)
console.log(req.body)
// const newMember = {
// id: uuid.v4(),
// name: req.body.name,
// email: req.body.email,
// active: true,
// }
// if(!newMember.name || !newMember.email) {
// return res.status(400).json({
// msg: "Please Fill in the Name or Email"}
// );
// }
// config.PEOPLE.push(newMember);
// res.json(config.PEOPLE);
})
module.exports = router
[我希望快速响应,我什至尝试了“ body-parser”模块,但这似乎也不起作用..我被卡住了..请问我该怎么办?
您的index.js文件中是否有3行?
// import body parser
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));