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

Node.js搜索接口报错:Cannot read properties of undefined (reading 'toLowerCase')

问题分析与解决

错误原因

报错Cannot read properties of undefined (reading 'toLowerCase')是因为z = req.body.search的值为undefined,此时调用toLowerCase()方法就会触发该错误。常见诱因有以下几种:

  • 缺少请求体解析中间件:Express默认不会自动解析POST请求的表单数据,若未配置express.urlencoded中间件,req.body本身就是undefined,自然取不到search字段。
  • 前端表单字段不匹配:前端搜索表单的输入框name属性不是search,导致提交后后端无法通过req.body.search获取值。
  • 提交数据异常:前端未正确以POST方式提交数据,或提交的请求体中没有search字段。

修复步骤

1. 配置请求体解析中间件

在Express应用初始化时添加以下代码,确保能解析表单格式的POST请求体:

// 要放在app.post('/search')路由之前
app.use(express.urlencoded({ extended: true }));
// 如果前端提交JSON格式数据,额外添加这行
// app.use(express.json());

2. 增加防御性检查,避免undefined调用方法

修改获取搜索关键词的代码,给z设置默认值,确保即使req.body.search不存在也不会报错:

// 原代码
// let z = req.body.search;
// 修改为
let z = req.body.search || '';
// 更严谨的写法
// let z = typeof req.body.search === 'string' ? req.body.search : '';

3. 修复后端调用alert的错误

后端Node.js环境中没有alert()函数,这行代码会触发新报错。如果需要提示用户无搜索结果,应把提示信息通过渲染页面传递给前端,在searchresults.ejs中显示:

// 原代码
// if (searchresult.length === 0) {
//     alert("Can't find what you are looking for");
// }
// 修改为
res.render('searchresults', {
    place: searchresult,
    noResultMsg: searchresult.length === 0 ? "Can't find what you are looking for" : ''
});

然后在searchresults.ejs中添加:

<% if (noResultMsg) { %>
    <p><%= noResultMsg %></p>
<% } %>

4. 验证前端表单配置

确保前端表单的method为POST,且输入框的name属性为search:

<form action="/search" method="POST">
    <input type="text" name="search" placeholder="输入搜索关键词">
    <button type="submit">搜索</button>
</form>

完整修复后的示例代码

let allPlaces = ['annapurna', 'bali', 'inca', 'paris', 'rome', 'santorini'];

// 先配置请求体解析中间件
app.use(express.urlencoded({ extended: true }));

app.post('/search', function (req, res) {
    let z = req.body.search || '';
    MongoClient.connect("mongodb://127.0.0.1:27017", function (err) {
        if (err) throw err;
        // let db = client.db('myDB');
        // let collection = db.collection('myCollection');
        let searchresult = [];

        for (let j = 0; j < allPlaces.length; j++) {
            if (allPlaces[j].includes(z.toLowerCase())) {
                searchresult.push(allPlaces[j]);
            }
        }

        res.render('searchresults', {
            place: searchresult,
            noResultMsg: searchresult.length === 0 ? "Can't find what you are looking for" : ''
        });
    });
});

内容的提问来源于stack exchange,提问作者Ahmed Haitham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:25:44