node.js - 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;
我似乎没有在任何地方关闭连接,那么为什么我只能向客户端写一条消息?
解决方案
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);
推荐阅读
- python - 如何检查密码要求?
- laravel - 具有多个外键的一对多关系 laravel
- delphi - 快速报表 VCL CrossObject 条件高亮
- python - 有没有直接的方法来识别原始点集中凸包点的索引?
- java - Apache poi 特定 Excel 模板文件容量损坏
- python - 同时使用动画和小部件matplotlib
- oracle - 以表数据类型作为输入参数的调用过程
- firebase-authentication - 带有用户信息的 Firebase 电话身份验证 expo-cli
- google-apps-script - 我一直在尝试为 facebook 创建一个社区连接器。我正在使用 OAuth2.0。单击身份验证按钮后,它给了我“无法加载 URL”错误
- html - 使用带有级联弹出菜单的框架