我正在尝试了解 JWT 以及它们如何与 Node 和 Express .js 配合使用。我有一个尝试使用 token 对用户进行身份验证的中间件:
app.use(function(req, res, next) {
if(req.headers.cookie) {
var autenticazione = req.headers.cookie.toString().substring(10)
autenticazione = autenticazione.substring(0, autenticazione.length - 3)
console.log(autenticazione)
jwt.verify(autenticazione, app.get('superSegreto'), function(err) {
if (err) {
res.send('authentication failed!')
} else {
// if authentication works!
next() } })
} else {
console.log('errore')} })
这是我 protected 网址的代码:
app.get('/miao', function (req, res) {
res.sendFile(__dirname + '/pubblica/inserisciutente.html')
res.end() })
即使路径是正确的(我什至尝试使用 path.join(__dirname + '/pubblica/inserisciutente.html) 并得到相同的结果),但在访问 url 时,我只是得到一个空白页面(里面甚至有 Node conde),我还设置了: app.use(express.static('/pubblica'))如果我尝试用 res.send('Some stuff') 替换 res.sendFile(..) 我可以在页面上正确查看它。我做错了什么?
最佳答案
res.sendFile()
是异步的,如果成功,它将结束自己的响应。
因此,当您在启动 res.sendFile()
后立即调用 res.end()
时,您将在代码实际发送文件之前结束响应。
你可以这样做:
app.get('/miao', function (req, res) {
res.sendFile(__dirname + '/pubblica/inserisciutente.html', function(err) {
if (err) {
res.status(err.status).end();
}
});
});
请参阅 res.sendFile()
的 Express 文档 here .
关于javascript - ExpressJs res.sendFile 在中间件之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201859/