简体   繁体   中英

forEach not working as expected in NodeJs

I am uploading the excel sheet in DB with the help of Nodejs, I am unable to authenticate and return the error as already exists the userid when the item.USER_ID already exists in DB. my server goes crashes and returns an error as Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Please help in the code how I fix this issue and make it, If the item.USER_ID already exists return error else insert.

var XLSX = require("xlsx");
const fs = require("fs");

try {
    const transaction = await con.transaction();
    var workbook = XLSX.readFile("myfile.xlsx");
    let json_data = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1);

    let count = 0;
    json_data.map(async (item) => {
        let stmt1 = await con.query("SELECT * FROM `table` WHERE `user_id` = :userid", { replacements: { userid: item.USER_ID }, type: con.QueryTypes.SELECT });
        if (stmt1.length > 0) {
            await transaction.rollback();
            return res.json({ message: "already exist the userid" });
        } else {
            let stmt2 = await con.query("INSERT INTO `table` (`user_id` , `user_name`) VALUES ( :user_id , :user_name)", {
                replacements: {
                    user_id: item.USER_ID,
                    user_name: item.USER_NAME,
                },
                type: con.QueryTypes.INSERT,
                transaction: transaction,
            });
            count++;
            if (count == json_data.length) {
                await transaction.commit();
                return res.json({ message: "file uploaded successfully.." });
            }
        }
    });
} catch (err) {
    await transaction.rollback();
    return res.json({ code: 500, message: { msg: "SQL ERROR" }, error: err.stack, status: "error" });
}

Here in your code, you are calling the res.json({ message: "file uploaded successfully.." }) inside json_data.map function.

since you are calling the res.json function inside an array, it'll be called as many times as of elements present in the array and as we know, we can sent only 1 response at a time for a request.
Because of which you're catching the errors Cannot set headers after they are sent to the client

just remove that res.json inside the map function, add it at the last of that particular map function.
I know you might question for the condition count == json_data.length you added to the code but javascript is async and this particular block can be executed before to that.

Hope this answer helps you. Please comment if you get any errors or have questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM