从 express 中的另一个函数写入 res
writing to res from another function in express
我不知道如何更好地描述我的问题。
也许代码会(这是非常基本的)
// in users route
var LIST = require('list.json')
/* GET users listing. */
router.get('/', function(req, res, next) {
res.write('beginning list')
writeList(function() {
res.end('list printed')
})
})
function writeList(cb) {
// some stuff
res.write(LIST)
cb()
}
所以在 tldr:
我想在主路由处理程序以外的函数中写入 res 对象。为什么这不起作用? (Error: Can't set headers after they are sent.
)
如何正确完成?
谢谢:)
你没有将 res 传递给你的函数,而是试图写入它,因此抛出异常关闭响应 object 并将 headers 设置为错误,当你调用res.end(),它已经关闭,所以你得到 headers 已经设置错误。
router.get('/', function(req, res, next) {
res.write('beginning list');
writeList( function(err, writeResult) {
if (err){
console.log(err);
res.end('Error');
}
else{
res.write(writeResult)
res.end('list printed')
}
})
});
function writeList(cb) {
// some stuff
cb(null, LIST)
}
我不知道如何更好地描述我的问题。 也许代码会(这是非常基本的)
// in users route
var LIST = require('list.json')
/* GET users listing. */
router.get('/', function(req, res, next) {
res.write('beginning list')
writeList(function() {
res.end('list printed')
})
})
function writeList(cb) {
// some stuff
res.write(LIST)
cb()
}
所以在 tldr:
我想在主路由处理程序以外的函数中写入 res 对象。为什么这不起作用? (Error: Can't set headers after they are sent.
)
如何正确完成?
谢谢:)
你没有将 res 传递给你的函数,而是试图写入它,因此抛出异常关闭响应 object 并将 headers 设置为错误,当你调用res.end(),它已经关闭,所以你得到 headers 已经设置错误。
router.get('/', function(req, res, next) {
res.write('beginning list');
writeList( function(err, writeResult) {
if (err){
console.log(err);
res.end('Error');
}
else{
res.write(writeResult)
res.end('list printed')
}
})
});
function writeList(cb) {
// some stuff
cb(null, LIST)
}