2
votes

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)
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')} })

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?

2
Please indent your code properly. Very hard to follow code that is improperly indented.jfriend00

2 Answers

11
votes

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) {
            res.status(err.status).end();
        }
    });
});

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

0
votes

if you want to end the response with res.end() then you must not mention or specify it after res.sendFile() because res.sendFile() is an asynchronous function that means it will take some time to execute and in that meantime next instruction which is in your case is res.end() will execute and that's why you didn't see any response send by the res.sendFile

You can visit the documentation to know more about res.sendFile() visit documentation