Express: Node crashes when I send a lot of the request in the same time

Created on 5 Jan 2019  路  1Comment  路  Source: expressjs/express

When I send a request one by one, all work good but I want to run a loop of the request to the same root and it show me a message.

ode:12333) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/home/oscarcode/Documents/oventsApi/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/oscarcode/Documents/oventsApi/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/oscarcode/Documents/oventsApi/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/home/oscarcode/Documents/oventsApi/node_modules/express/lib/response.js:158:21)
    at getAllValuationsByUserName (/home/oscarcode/Documents/oventsApi/Controles/userPhoto/valuations/getAllValuationsByUserName.js:43:32)
    at process.internalTickCallback (internal/process/next_tick.js:77:7)
(node:12333) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 19)

this is all my code.

async function isAuth(req, res, next) {
    if (!req.headers.authorization) {
        return res.status(403).send({
            message: 'No tienes autorizacion'
        });
    }
    const token = req.headers.authorization.split(' ')[1];
    try {
        await jwt.verifyToken(token, config.SECRET_TOKEN, {});
        next();

    } catch (e) {
        return res.status(500).send({
            toke: 'Token no valido'
        })
    }

}
router.get('/getAllUsers', isAuth, async function getAllUsers(req, res, next){
  try {
    const users =  await User.find({})
    if (!users) {
      error.message = "Users not found";
      return res.status(404).json({ error });
    }else{
      return res.send({
        users,
        error: false
      });
    }

  } catch (error) {
    res.status(400).send({
      users:[],
      error: error
    })
  }
}); 

and this is my script with that i'm testing.

var request = require("request");

let num = 0
while (num < 20) {
    var options = {
        method: 'GET',
        url: 'http://localhost:3003/api/getAllValuationsByUserName/alo?skip=0&limit=10',
        headers:
        {
            'Postman-Token': '681e1613-3021-4d2a-8950-c481a2300f37',
            'cache-control': 'no-cache',
            Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1YmExYjVjZDBiMjM5MDM3YmNmYjliOTMiLCJuYW1lIjoiZ2RhMTMiLCJkYXRlIjoiMjAxOC0wOS0xOVQwMjozNDo1My45NjJaIiwic2VzaW9uIjp0cnVlLCJpYXQiOjE1MzczMjQ0OTR9.cWXLDBSVjEBMpcXOPojJWehvcu0eLtX_ecJN1C0Sp4o'
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
    });
    console.log(num)
    num++
}
question

Most helpful comment

It looks like your code crashes in file /home/oscarcode/Documents/oventsApi/Controles/userPhoto/valuations/getAllValuationsByUserName.js on line 43 while executing a callback.

Your problem in reality consists of two problems:

Unhandled promise rejection

This one is certainly a problem with your code

You are (1) not .catch()ing a promise rejection or (2) there's an async function containing a part not wrapped in try/catch which throws an error.
See code below:

Edit: After looking again at the error message you get, I think that it's the second variant - unhandled error in async function. This uncaught error is thrown, because you set headers after they are sent (see the next section in bold).

(1)

function willReject(){
    return new Promise((resolve, reject) => {
        reject("Rejected by willReject function");
    });
}

willReject();
/* This results in:
(node:15824) UnhandledPromiseRejectionWarning: Rejected by willReject function
(node:15824) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15824) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
*/

// This is correct
willReject()
    .catch(err => {
        console.error("Oh no! There was an error!\nSee message below:");
        console.error(err);
    });

(2)

function willError(){
    throw new Error("An error form willError function");
}

async function wrong(){
    willError();
}

wrong();
/* Doesn't it look similar to your error message?
(node:14408) UnhandledPromiseRejectionWarning: Error: An error form willError function
    at willError (D:\xxx\express_3847\__a.js:2:8)
    at wrong (D:\xxx\express_3847\__a.js:6:2)
    at Object.<anonymous> (D:\xxx\express_3847\__a.js:9:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:342:17)
(node:14408) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14408) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
*/

// That's how it should be done.
async function correct(){
    try {
        willError();
    } catch (error) {
        console.error("Oh no! There was an error!\nSee message below:");
        console.error(error);
    }
}
correct();

Setting response headers after they are sent to the client

I'm almost sure that this also isn't a problem with Express

It's hard to diagnose why exactly it's crashing like this, because the code, which causes this error, sends a request to /api/getAllValuationsByUserName/alo, while you have only provided code for /getAllUsers. In order for someone to help you, you should provide more information. I also think that's not a problem with Express, but your application. IMO this question is more suitable for StackOverflow.

Maybe this StackOverflow question will help you fix the problem.

>All comments

It looks like your code crashes in file /home/oscarcode/Documents/oventsApi/Controles/userPhoto/valuations/getAllValuationsByUserName.js on line 43 while executing a callback.

Your problem in reality consists of two problems:

Unhandled promise rejection

This one is certainly a problem with your code

You are (1) not .catch()ing a promise rejection or (2) there's an async function containing a part not wrapped in try/catch which throws an error.
See code below:

Edit: After looking again at the error message you get, I think that it's the second variant - unhandled error in async function. This uncaught error is thrown, because you set headers after they are sent (see the next section in bold).

(1)

function willReject(){
    return new Promise((resolve, reject) => {
        reject("Rejected by willReject function");
    });
}

willReject();
/* This results in:
(node:15824) UnhandledPromiseRejectionWarning: Rejected by willReject function
(node:15824) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15824) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
*/

// This is correct
willReject()
    .catch(err => {
        console.error("Oh no! There was an error!\nSee message below:");
        console.error(err);
    });

(2)

function willError(){
    throw new Error("An error form willError function");
}

async function wrong(){
    willError();
}

wrong();
/* Doesn't it look similar to your error message?
(node:14408) UnhandledPromiseRejectionWarning: Error: An error form willError function
    at willError (D:\xxx\express_3847\__a.js:2:8)
    at wrong (D:\xxx\express_3847\__a.js:6:2)
    at Object.<anonymous> (D:\xxx\express_3847\__a.js:9:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:342:17)
(node:14408) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14408) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
*/

// That's how it should be done.
async function correct(){
    try {
        willError();
    } catch (error) {
        console.error("Oh no! There was an error!\nSee message below:");
        console.error(error);
    }
}
correct();

Setting response headers after they are sent to the client

I'm almost sure that this also isn't a problem with Express

It's hard to diagnose why exactly it's crashing like this, because the code, which causes this error, sends a request to /api/getAllValuationsByUserName/alo, while you have only provided code for /getAllUsers. In order for someone to help you, you should provide more information. I also think that's not a problem with Express, but your application. IMO this question is more suitable for StackOverflow.

Maybe this StackOverflow question will help you fix the problem.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

despairblue picture despairblue  路  3Comments

Domiii picture Domiii  路  3Comments

wxs77577 picture wxs77577  路  3Comments

prashantLio picture prashantLio  路  3Comments

HafidAbnaou picture HafidAbnaou  路  3Comments