使用 Node 在 Express 中发送后无法设置 headers
Can't set headers after they are sent in Express using Node
我正在使用 express 和 ejs、res、end() 制作模板。但是没有找到任何解决方案。我已经尝试了很多东西,比如 next()
下面是我的代码:
app.get('/', function (req, res, next) {
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
var data = JSON.stringify(mainmenu);
return res.render('index', {items : data});
res.end();
});
connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
var dataHome = JSON.stringify(homecontent);
return res.render('index', {homeitem : dataHome});
res.end();
connection.release();
});
});
});
这会给我错误:
Error: Can't set headers after they are sent.
谁能帮帮我?
每个查询都试图将完整响应发送回浏览器,因此第二个查询失败。尝试这样的事情:
app.get('/', function (req, res, next) {
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
//got the results of the first query
var posts = JSON.stringify(mainmenu);
connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
//got the results of the second query
var dataHome = JSON.stringify(homecontent);
//return both
return res.render('index', {homeitem : dataHome, items : data});
//close connection
res.end();
//release connection
connection.release();
});
});
});
我正在使用 express 和 ejs、res、end() 制作模板。但是没有找到任何解决方案。我已经尝试了很多东西,比如 next()
下面是我的代码:
app.get('/', function (req, res, next) {
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
var data = JSON.stringify(mainmenu);
return res.render('index', {items : data});
res.end();
});
connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
var dataHome = JSON.stringify(homecontent);
return res.render('index', {homeitem : dataHome});
res.end();
connection.release();
});
});
});
这会给我错误:
Error: Can't set headers after they are sent.
谁能帮帮我?
每个查询都试图将完整响应发送回浏览器,因此第二个查询失败。尝试这样的事情:
app.get('/', function (req, res, next) {
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
//got the results of the first query
var posts = JSON.stringify(mainmenu);
connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
//got the results of the second query
var dataHome = JSON.stringify(homecontent);
//return both
return res.render('index', {homeitem : dataHome, items : data});
//close connection
res.end();
//release connection
connection.release();
});
});
});