首页 > 解决方案 > NodeJS 无法向客户端发送消息

问题描述

我正在尝试学习 Node.JS,但使用本教程制作 REST API: https ://medium.freecodecamp.org/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

我有一个非常愚蠢的小问题,我似乎无法解决。在我的 user_routes.js 文件中,我试图向 express() 应用程序写入几条消息,但是在第一次 res.send() 调用之后它永远不会工作。为什么是这样?我在我的代码中找不到关闭连接或其他任何地方的任何地方,那么为什么我不能多次写入请求?

我的 user_routes.js

    module.exports = function(app, db) {
    app.post('/user', function (req,res) {
        res.send("User Request Recieved via POST");

        // Add the user to the database, if they don't already exist
        const firstName = req.body.firstName;
        const lastName = req.body.lastName;
        const email = req.body.email;
        const password = req.body.password;

        const user = {
            firstName: firstName,
            lastName : lastName,
            email : email,
            password : password
        };

        if (db.collection('users').find({'email':email}).count() == 0) {
            res.send('Unique Email');
            db.collection('users').insert(user, (err, result) => {
                if (err) {
                    console.log("error");
                } else {
                    console.log(result.ops[0])
                }
            });
        } else {
            res.send("Email already in use")
        }

    })
};

任何我的 server.js:

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 6969;
const db = require('./config/db')

// We need to decode data from the url using the body-parser lib
app.use(bodyParser.urlencoded({ extended: true }));

MongoClient.connect(db.url).then( function(db) {
    require('./app/routes')(app, db);
    app.listen(port, () => {
      console.log('We are live on ' + port);
    });               
}).catch (function (err) {
    console.log(err);
});     


module.exports = app;

我似乎没有在任何地方关闭连接,那么为什么我只能向客户端写一条消息?

标签: node.js

解决方案


res.send() == return()

res.send() 相当于您的帖子的“return”——每次调用只能执行一次。

每个 res.send() 多条消息

如果您想通过一次调用发送多条消息,您需要编译一个要发送的消息对象/数组,并通过 res.send() 发送该对象/数组。例子:

ret_msg = [];
ret_msg.push("Here's your first message.");
ret_msg.push("Here's your second message.");
ret_msg.push("Here's your third message.");

res.send(ret_msg);

推荐阅读