ExpressJs res.sendFile doesn't work after middleware

skjorrface Source

I'm trying to understand JWT and how they work with Node and Express .js. I have this middleware that tries to authenticate users with a 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)
jwt.verify(autenticazione, app.get('superSegreto'), function(err) {
  if (err) {
    res.send('authentication failed!')
  } else {
  // if authentication works!
    next() } })
   } else {
    console.log('errore')} })

And this is the code for my protected url:

app.get('/miao', function (req, res) {

res.sendFile(__dirname + '/pubblica/inserisciutente.html')
res.end() })

Even though the path is correct (I even tried with path.join(__dirname + '/pubblica/inserisciutente.html) and got the same result), when visiting the url I just get a blank page (with even node conde inside) I also set: app.use(express.static('/pubblica')) P.S. if I try to replace res.sendFile(..) with res.send('Some stuff') I can correctly view it on the page. What am I doing wrong?



answered 3 years ago jfriend00 #1

res.sendFile() is asynchronous and it will end its own response if it is successful.

So, when you call res.end() right after you start res.sendFile() you are ending the response before the code has actually sent the file.

You can do it like this:

app.get('/miao', function (req, res) {

    res.sendFile(__dirname + '/pubblica/inserisciutente.html', function(err) {
        if (err) {

See the Express doc for res.sendFile() here.

comments powered by Disqus