Expressredirect错误:发送后无法设置标题

当这段代码碰到redirect行时,它会抛出'发送错误后无法设置标题',并且不会redirect。 我有罪不完全理解标题和expression如何与他们合作。 这个关于这个错误的链接让我困惑了一下,可能是因为我对于发生了什么事情没有足够的了解。 此外,我知道这是一个朴素的authentication方法,但我只是想要基本的东西工作。

app.post('/api/login', function(req, res) { if (req.body.password === auth.password) { auth.date = new Date() res.redirect('/admin') } else { console.log("wrong pw") } }) 

更新:谢谢你@Brendan阿什沃斯我错过了一个明显的其他,现在我已经添加,不再有错误。

但是这行不会改变我的页面的内容

 res.sendfile('./public/admin/views/tunes.html') 

它工作之前我用auth检查包装它

 var auth = require('../config/auth') module.exports = function(app) { /* * CONTENT API */ //... /* * Admin Routes */ app.get('/admin/login', function(req, res) { res.sendfile('./public/admin/views/login.html') }) app.post('/api/login', function(req, res) { if (req.body.password === auth.password) { auth.date = new Date() res.redirect('/admin') } else { res.json({message: 'Wrong password!'}) } }) app.get('/admin', function(req, res) { if (auth.date) { res.sendfile('./public/admin/views/tunes.html') console.log("test") // } else { //added else res.redirect('/admin/login') } }) app.get('/admin/:url', function(req, res) { if (auth.date) { res.sendfile('./public/admin/views/' + req.params.url + '.html') } else { //added else res.redirect('/admin/login') } }) // frontend routes // route to handle all angular requests app.get('*', function(req, res) { res.sendfile('./public/views/index.html') }) 

}

最终更新! 我需要的最后一件事是发送文件后处理redirect客户端。 简单的authentication工作现在完美!

  $http.post('/api/login', $scope.auth).success(function() { window.location.href = '/admin' }) 

错误的解释Can't set headers after they are sent error

所有的HTTP响应都遵循这个基本结构:

 .. Response Line .. .. Headers .. .. Body .. 

如果你想redirect一个用户,首先Response Line行将被发送redirect代码(可以说300),然后Headers将被发送一个Location: xxx头。

那么,我们终于可以发送一个正文(不是在redirect的情况下,但总的来说)。 然而 – 在你的代码的情况下 – 你正在发送Body响应, 然后试图redirect用户。 由于标题(和响应行)已经被发送(因为你发送了正文),所以它不能在正文之后发送更多的标题。

你的代码中的一个例子是:

 app.get('/admin', function(req, res) { if (auth.date) { res.sendfile('./public/admin/views/tunes.html') } res.redirect('/admin/login') }) 

如果我假设正确,你实际上想res.sendfile()调用后return 。 如果auth.date是真的,那么你会发送一个文件(即身体响应),然后给一个redirect代码 – 这是行不通的。