英文:
'Cannot read properties of undefined (reading 'name')'
问题
router.post('/add', (req, res) => {console.log(req.body.name)})
英文:
localhost:4000 can load Appointment.html properly but when i click on button submit it get routed to localhost:4000/add and shows errorCannot read properties of undefined (reading 'name')
app.js
const app = express();
const bodyParser = require('body-parser');
const router = require('./route/router');
app.use(router)
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json);
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.listen(4000);
router.js
const express = require('express');
const bodyParser = require('body-parser');
const controller = require('../controller/controller');
const router = express.Router();
router.get('/',controller.homePage);
router.get('/add',controller.getItem);
router.post('/add',(res,req)=>{console.log(res.body.name)})
module.exports = router;
controller.js
const { query } = require('express');
const Item = require('../models/item')
exports.getItem = (req, res, next) => {
console.log('get!'+req)
}
exports.postItem = (req, res, next) => {
console.log(req.body.name)
};
exports.homePage = (req, res, next) =>{
res.sendFile(__dirname + '/Appointment.html');
}
答案1
得分: 0
在 router.js 中尝试添加一行代码:router.use(express.json());
因为当你从客户端传递 body 时,如果传递的是一个对象,它无法解构。同时,在客户端发出请求时,确保前端将对象传递为 {name: "name", ...}。确保对象的键名与你尝试解构的键名完全相同。
英文:
In router.js try adding one line router.use(express.json());
As when you pass body from client if you are passing as an object it can’t de structure it. And while making request from client side also said frontend pass object as {name : “name”, ….}. Make sure the key name of the object is exactly same as you’re trying to de structure.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论