0

I am developing a webapp using nodejs, I make the register using request.session, and I use ajax to make a request, when I use a conditional to get some information (an ID) I get an error.

router.post("/admin", function(request, response){  
    var data = {};

    sess = request.session;
    sess.username = request.body.input_user_admin;
    sess.password = request.body.input_password_admin;

    if(sess){
        // Verificate user existence (in a database) to login
        if(loginFunctions.userIsRegistered(sess.username, sess.password, admins)){
            for(var i=0; i<admins.length; i++){
                if(admins[i].name == sess.username && admins[i].password==loginFunctions.md5(sess.password)){
                    i = admins.length;
                    data["devices"] = devices;
                    data["users"] = users;
                    data["sess"] = sess;
                    response.render('admin', data);
                }
            }
        }
        else{
            response.redirect('/adminLogin');
        }
    }

    else if(request.body["idUserToDelete"]){
        console.log("SISAS ÑOTE");
        Users.remove({"_id": request.body["idUserToDelete"]}, function(err){});
        updateUsersReading();
        data["devices"] = devices;
        data["users"] = users;
        //response.send(data);
    }

    else if(request.body["dataCodes"]){
        updateDataFromCodesAdmin(request.body);
        updateDevicesReading();

        data["devices"] = devices;
        data["users"] = users;

        response.render('admin', data);
    }

    else if(request.body["newDevices"]){
        addNewDevicesToDB(request.body, sess, response);
        updateDevicesReading();
        data["devices"] = devices;
        data["users"] = users;
        response.render('admin', data);
    }

    else{
        response.redirect('/adminLogin');
    }
});

This is the error

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11

And in general, How can I send data like answer to an ajax request to the view (admin.jade), so I use response.send(data) and I have problems?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    `response.redirect` works by modifying the headers sent to the client, but headers always have to be changed before any output is sent to browser. Once output is generated, headers can't be modified, as they are already sent. – adeneo Jan 06 '16 at 04:51
  • http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent – adeneo Jan 06 '16 at 04:53
  • In for(var i=0; i1 or ==1? – Ketha Kavya Jan 06 '16 at 10:20

0 Answers0