如何将express.js响应对象传递给另一个模块
问题描述:
大家好,我正尝试将一个快速响应对象传递给我拥有的其他模块。所以在我的server.js
文件我有这个如何将express.js响应对象传递给另一个模块
const room = require('../controller/rooms_controller')
app.post('/rooms', function(req, res){
var name = req.body.roomname
var loc = req.body.loc
room.newRoom(name, loc, res)
})
所以我试图将res
对象传递给rooms_controller
模块。现在我rooms_controller模块看起来像这样
const Room = require('../models/room')
exports.newRoom = function(name, loc, res){
Room.findOne({'location': loc}, function(err, room, res){
if(err){
res.send({err: err})
}
if(room){
res.send({room: room})
}else{
var newRoom = new Room()
newRoom.location = loc
newRoom.name = name
newRoom.save(function(error){
if(err){
res.send({ error: error })
}
res.send({room: newRoom})
})
}
})
}
所以在我的数据库越来越创建的记录,但我得到了cannot read property send of undefined
错误在我的终端。任何人都可以帮助我这个。将不胜感激,
答
你做正确,而是因为你重新定义这条线
Room.findOne({'location': loc}, function(err, room, res){
所以资源正在覆盖资源从Room.findOne
代替参数newRoom
响应这是您的实际响应对象。为其中一个使用不同的变量名称。
'room'是'findOne'的回应,我不认为回调实际上通过了第三个参数。 – robertklep
虽然我不知道这个函数是什么,它最有可能是@robertklep描述的情况,这意味着你可以完全删除回调函数的第三个参数。 – Froast
非常感谢。 :) – Shadid