从数据库获取方法会导致套接字挂起错误

问题描述 投票:0回答:2

我想从数据库中获取所有用户的数组。这导致套接字挂起错误。有人可以帮忙吗?谢谢!这是在Glitch上的项目的链接:Glitch project这里是有问题的代码:

app.get("/api/exercise/users", (req, res) => {
  userModel.find({}), (err, data) => {
      if (err) {
        res.send("Error reading the database.");
      } else {
        let nameAndId = data.map(user => {
           return { username: user.username, id: user._id };
        });
        res.send(nameAndId);
      }
    };
});
这是错误:

/opt/debugger/node_modules/.registry.npmjs.org/http-proxy/1.16.2/node_modules/http-proxy/lib/http-proxy/index.js:119
    throw err;
    ^
Error: socket hang up
    at createHangUpError (_http_client.js:323:15)
    at Socket.socketCloseListener (_http_client.js:364:25)
    at Socket.emit (events.js:194:15)
    at TCP._handle.close (net.js:597:12)
javascript node.js mongodb express mongoose
2个回答
0
投票

这可能是由于您在服务器上进行监听的方式所致。试试:

const http = require('http');
const server = http.createServer(app);

server.listen(port, () => {
  console.log('Listening on %d', server.address().port);
});

0
投票

已解决!一个简单的错误,这是工作代码:

app.get("/api/exercise/users", (req, res) => {
  userModel.find({}, ( err, data) => {
      if (err) {
        res.send("Error reading the database.");
      } else {
        let nameAndId = data.map(user => {
           return { username: user.username, id: user._id };
        });
        res.send(nameAndId);
      }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.