当此代码到达重定向行时,它会抛出“发送后无法设置 header 错误”并且不会重定向。我对没有完全理解标题以及 express 如何与它们一起工作感到内疚。 This link about this error让我有点困惑,可能是因为我对正在发生的事情没有足够基本的了解。另外,我知道这是一种有点天真的身份验证方法,但我只是想让基本的东西起作用。
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 Ashworth 我错过了一个明显的 else,我现在添加了它并且不再收到错误。
然而这一行并没有改变我页面的内容
res.sendfile('./public/admin/views/tunes.html')
在我用身份验证检查包装它之前它起作用了
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')
})
最后更新!!我需要做的最后一件事是在发送文件后处理重定向客户端。简单的身份验证现在可以完美地工作了!
$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 ..
如果你想重定向一个用户,首先 Response Line
会被发送一个重定向代码(比方说 300),然后 Headers
会被发送一个位置:xxx
header 。
然后,我们终于可以发送一个主体(不是在重定向的情况下,而是一般情况下)。但是 - 对于您的代码 - 您正在发送 Body
响应 then 尝试重定向用户。由于 header (和响应行)都已发送(因为您发送了正文),它无法在正文之后发送更多 header 。
您的代码中的一个例子是:
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
是真实的,那么您将发送一个文件(即正文响应),然后提供重定向代码 - 这是行不通的。
关于node.js - 快速重定向错误 : can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372080/