giudaballerino
giudaballerino

Reputation: 65

NodeJS - Server responds with 404 and then loads the page

Does someone understand what's going on in my nodeJS application. When I do an asynchronous call using ajax the server first responds with a 404 error then loads the page. The application works fine but I have a lot of boring logs saying "Can't set headers after they are sent."

Here is the route part

module.exports = function(passport) {
          var router = express.Router();
          ........
          router.get('/dashboard', isLogged, dashcontroller.showdashboard);
          router.get('/dashboard/general', isLogged, dashcontroller.general);
          ........
          return router;
    }

here the controller

exports.showdashboard = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('dashboard', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}


exports.general = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('general', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}

The asynchronous request, this code is reachable by the client from /dashboard and resides in public/javascripts/code.js. The client found it and executes it with no problems.

$(function() {
    $("li.infos").click(function() {
      $("li.basket").removeClass("active")
      $("li.infos").addClass("active")
        $('.main-container')
           .load('/user/dashboard/general');
    });
});

All works fine but i still get those boring logs

GET /stylesheets/dashboard.css 304 0.555 ms - -
GET /javascripts/dashboard.js 304 0.280 ms - -
GET /javascripts/basket.js 304 0.323 ms - -
abc deserializeUser
Executing (default): SELECT `id`, `username`, `public_key`, `email`, `password`, `last_login`, `basketcount`, `status`, `activation_token`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = 6;

GET /user/dashboard/general 404 35.837 ms - 2290
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/home/me/Documents/app/node_modules/express/lib/response.js:730:10)
and the trace goes on

Does anyone understand what is happening? thank you in advice

Upvotes: 0

Views: 182

Answers (1)

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

Can't set headers after they are sent." is not a boring log message.

You are calling next() after writing http response, that's why you are facing the issue. e.g.

exports.showdashboard = function(req, res, next) {
   if (req.user.status == 'active')
     return res.render('dashboard', { title: 'title' , user: req.user});
   else
     return res.redirect('/user/logout');
}

and, same with exports.general.

Upvotes: 1

Related Questions