‘Cannot read properties of undefined (reading ‘name’)’

huangapple go评论67阅读模式
英文:

'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.

huangapple
  • 本文由 发表于 2023年7月20日 10:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定