You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express、Ejs、body-parser时出现Cannot Read property 'city' of undefined报错

解决Node.js + Express + EJS中"Cannot Read property 'city' of undefined"错误

Hey there, let’s dig into why you’re running into this frustrating error. This issue almost always stems from how your app is handling form data or accessing the request body—let’s walk through the most common fixes step by step.

1. 确认body-parser已正确配置并启用

If you haven’t set up body-parser properly, req.body will be undefined, which is exactly why you’re getting the "cannot read 'city' of undefined" message.

Make sure you’ve installed body-parser first (npm install body-parser), then add this configuration to your server.js before defining your routes:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// 处理表单提交的url编码数据(这是表单默认的编码方式)
app.use(bodyParser.urlencoded({ extended: true }));

// 如果你的应用还处理JSON请求,也可以加上这个,但表单提交一般用上面的就行
// app.use(bodyParser.json());

2. 检查你的EJS表单设置

Your form needs to send data via POST (since GET requests don’t have a request body) and the input field for "city" must have the correct name attribute. Without the name attribute, the data won’t be included in the request body.

Here’s a corrected example for your index.ejs form:

<form action="/your-submit-route" method="POST">
  <label for="city">City:</label>
  <input type="text" id="city" name="city" placeholder="Enter your city">
  <button type="submit">Submit</button>
</form>
  • Double-check the action matches the route you’re handling in server.js
  • Ensure the method is set to POST (not GET)
  • The name="city" is critical—this is how req.body.city gets populated

3. 确保你的路由处理的是POST请求

If you’re trying to access req.body.city in a GET route, it will always be undefined because GET requests don’t include a request body. Make sure your route uses app.post() instead of app.get().

Example of a correct POST route in server.js:

app.post('/your-submit-route', (req, res) => {
  // 先调试一下,看看req.body到底是什么
  console.log('Request body:', req.body);

  // 安全访问city字段,避免报错
  const userCity = req.body?.city || 'No city provided';
  res.render('index', { city: userCity });
});

The optional chaining operator (?.) here is a nice safety net—it prevents the error if req.body is undefined.

Quick Debug Tip

If you’re still stuck, add console.log(req.body) at the top of your route handler. If it logs undefined, go back to step 1 and double-check your body-parser setup. If it logs an object but doesn’t have a city property, check your form’s name attribute again.


内容的提问来源于stack exchange,提问作者Prince Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:00:04