0

I want to save an array of strings, but I am getting the following error:

Error: Can't set headers after they are sent.

this is my code to save:

router.post('/addalluserskills', function(req, res){
    console.log(req.body);
        var userSkill = new UserSkill();
        userSkill.email = req.session.email;

    for (var i = 0; i < req.body.mySkills; i++){

        userSkill.user_skill_id = req.body.mySkills[i];
        userSkill.save(function(err){
        if(err) return res.send(err);
        res.json({
            message: '201: Successfully added skill'
        });
    });
    }

});

Can't I do a save twice? I don't understand what could be the problem here. Is the connection still open and I need to close before sending another one?

Edited:

Answer:

router.post('/addalluserskills', function(req, res){

    for (var i = 0; i < req.body.mySkills.length; i++){
        var userSkill = new UserSkill();
        userSkill.email = req.session.email;
        userSkill.user_skill_id = req.body.mySkills[i];
        userSkill.save(function(err){
        if(err) return res.send(err);

    });
    }
            res.json({
                message: '201: Successfully added skill'
            });

});

1 Answer 1

1

send the response after the whole array process is done,

previously your req.body.mySkills contains the array, you process the first element from array and save it and do res.json and again the the 2nd element from the array is processed and you are send the response header res.json again, which will throw an error Error: Can't set headers after they are sent. because you already had send the response headers.

router.post('/addalluserskills', function (req, res) {
    console.log(req.body);
    var userSkill = new UserSkill();
    userSkill.email = req.session.email;

    for (var i = 0; i < req.body.mySkills; i++) {
        userSkill.user_skill_id = req.body.mySkills[i];
        userSkill.save(function (err) {
            if (err) return res.send(err);
        });
    }
    res.json({
        message: '201: Successfully added skill'
    });

});
Sign up to request clarification or add additional context in comments.

3 Comments

I've added the complete correct answer to my initial question. But I will upvote your answer, because it helped.
mine solution was for Error: Can't set headers after they are sent, and I provided you that. It's up to you later how you handle the code, modify it. It's the solution and you have to accept it
and you shouldn't do var userSkill = new UserSkill(); inside the for loop, you will creating same instances multiple times... reapeating same work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.