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

笔记应用点击保存报错:Cannot read properties of undefined (reading 'push')求助

笔记应用保存功能错误排查与修复

错误原因

TypeError: Cannot read properties of undefined (reading 'push') 错误出现在Note.js的addNewNote函数中,说明调用该函数时传入的noteList参数是undefined。

追踪代码可知,api index.js中通过const {db} = require('../db/db.json')导入数据:

  • 若db/db.json文件不存在、为空,或文件内容不是包含db属性的JSON对象,解构得到的db会是undefined
  • 调用addNewNote(req.body, db)时传入undefined,执行noteList.push就会触发错误

修复步骤

1. 确保初始数据库文件格式正确

检查db/db.json文件:

  • 如果文件不存在,创建该文件,写入初始内容:{"db": []}
  • 如果文件已存在,确保内容是包含db数组的JSON结构,而非空内容或其他格式

2. 优化数据库读取逻辑,避免undefined

修改api index.js的导入部分,添加文件读取错误处理,确保db始终为数组:

const router = require('express').Router();
const fs = require('fs');
const path = require('path');
const { addNewNote, removeNote} = require('../lib/note.js');

// 读取并初始化数据库,处理异常情况
let db;
try {
  const dbContent = fs.readFileSync(path.join(__dirname, '../db/db.json'), 'utf8');
  const parsedData = JSON.parse(dbContent);
  // 确保db是数组,否则初始化为空数组
  db = Array.isArray(parsedData.db) ? parsedData.db : [];
} catch (err) {
  // 文件不存在或解析失败时,初始化为空数组
  db = [];
}

router.get('/notes', (req, res) => {
    res.json(db);
})

router.post('/notes', (req, res) => {
    const newNote = addNewNote(req.body, db);
    res.json(newNote);
})

router.delete('/notes/:id', (req, res) => {
    removeNote(req.params.id, db);
    res.json(req.body);
})

module.exports = router;

3. 给工具函数添加参数容错处理

修改Note.js中的函数,确保noteList始终为数组,同时避免无效操作:

const path = require('path');
const fs = require('fs');
const uniqid = require('uniqid');

function findById(id, noteList) {
    noteList = noteList || [];
    return noteList.filter(note => note.id === id)[0];
}

function addNewNote(body, noteList) {
    // 确保noteList是数组
    noteList = noteList || [];
    let newNote = { ...body }; // 复制body对象,避免修改原请求体
    newNote.id = uniqid();
    noteList.push(newNote);
    fs.writeFileSync(
        path.join(__dirname, '../db/db.json'),
        JSON.stringify({db: noteList}, null, 2)
    );
    return newNote;
}

function removeNote (id, noteList) {
    noteList = noteList || [];
    const removeThisNote = findById(id, noteList);
    // 如果未找到目标笔记,直接返回
    if (!removeThisNote) return;
    
    for (let i = 0; i < noteList.length; i++){
        if (noteList[i].id === removeThisNote.id) {
            noteList.splice(i, 1);
            fs.writeFileSync(
                path.join(__dirname, '../db/db.json'),
                JSON.stringify({db: noteList}, null, 2)
            );
            break; // 删除后跳出循环,避免重复执行
        }
    };
}

module.exports = {
    findById,
    addNewNote,
    removeNote
};

4. Heroku部署注意事项

Heroku的文件系统是临时文件系统,应用重启后所有写入的文件会丢失。如果需要持久化笔记数据,建议:

  • 使用Heroku提供的Postgres数据库
  • 集成第三方云存储服务存储JSON数据

内容的提问来源于stack exchange,提问作者Icaro Araujo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:10:34