【问题标题】:NodeJS without frameworks: findById没有框架的 NodeJS:findById
【发布时间】:2021-12-18 18:52:03
【问题描述】:

我是初学者,正在尝试使用 NodeJS 和 JSON 文件创建一个函数 findByID 作为没有框架的数据库,代码:

const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
    const server = http.createServer((req, res) => {
        const urlparse = url.parse(req.url, true);
      if (urlparse.pathname == "/todos" && req.method == "GET") {
          const search = urlparse.search;
          if (search) { 
            const [, query] = urlparse.search.split("?");
            const data = querystring.parse(query);
            todos = todos.filter((todo) =>  todo.id === data.id);
            res.end(JSON.stringify(todos, null, 2));
          }
        }})

当我第一次向邮递员查询时,一切都很好。 1st request

当我第二次在响应窗口中检查时,有一个空数组。2nd request

每个请求使用不同的 id。

【问题讨论】:

  • todos 来自哪里?
  • @litelite,添加了部分代码

标签: javascript node.js postman


【解决方案1】:

我没有看到 todos 定义,所以我假设它是全局的,这行然后在每个请求中改变它:

todos = todos.filter((todo) =>  todo.id === data.id);

另一件事是,如果 id 是唯一的,您可以使用 todos.find 来获得第一个匹配项。

所以改为使用新变量并查找:

const todoMatch = todos.find((todo) =>  todo.id === data.id);

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 2012-08-20
    • 2012-03-28
    • 2014-05-25
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2014-08-04
    相关资源
    最近更新 更多