3

Help me :(, i cannot find solution for my error, i try using return before my response it dosen't work

this my code

function isAuthenticated(req, res, next) {
var getToken = req.cookies.token;
var getUrl = req.originalUrl;
console.log(getToken)    
if(getToken == undefined) {
    res.redirect('/login')
    next()
} else {
    console.log('success')
    next()
}
next() }

router.get('/login', isAuthenticated, auth.login);
router.get('/logout', isAuthenticated, auth.logout);
router.post('/logging', auth.prosesLogin);
Subiyantoro
  • 85
  • 1
  • 2
  • 7
  • 2
    Possible duplicate of [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – ponury-kostek Jul 09 '17 at 11:23
  • you have solution for my code? – Subiyantoro Jul 09 '17 at 11:30
  • 1
    Remove `next()` after `else { }` and in the `if` condition. You must redirect to the endpoint only if authentication has been successful (i.e. calling `next()`). Otherwise, you must redirect to `/login`. (here is fiddle: https://jsfiddle.net/h0e2hsau/1/ ) – oneturkmen Jul 09 '17 at 11:48
  • but wait it's still loop,. GET /auth/logout and, my error it's not show up anymore, but still not redirect to /auth/login url :( – Subiyantoro Jul 09 '17 at 12:02
  • @Subiyantoro remove `isAuthenticated` from `GET @ /login` endpoint. No point to validate if person is not logged in yet, right? – oneturkmen Jul 09 '17 at 12:03
  • @alwaysone yes that's right, but later i want GET @ /login using isAuthenticated middleware to for checking if user request to url @ /login and authenticated it will be redirect to another page. that's code for example i testing my middleware for redirecting page but still error :( – Subiyantoro Jul 09 '17 at 12:11
  • Let's move to the chat [here](http://www.e-chat.co/room/220911) – oneturkmen Jul 09 '17 at 12:16
  • @alwaysone i'm on :) – Subiyantoro Jul 09 '17 at 12:24

2 Answers2

4

It seems that in your functions, the order of function arguments is wrong.

Instead of (err, res) make (req, res) or (err, req, res, next). Hope this helps.

oneturkmen
  • 1,288
  • 1
  • 11
  • 27
3

Replace next() with return false.

Dan King
  • 564
  • 10
  • 18