forEach not working as expected in NodeJs – JavaScript – SitePoint - Freelance Find

Breaking

Monday, September 5, 2022

forEach not working as expected in NodeJs – JavaScript – SitePoint

I am uploading the excel sheet in DB with the help of Nodejs, I am unable to authenticate and return the error as already exist the userid when the item.USER_ID already exists in DB. my server goes crash 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" });
}

A possible clue is from https://stackoverflow.com/questions/26307920/res-json-cant-set-headers-after-they-are-sent where they say that res.json results in sending a response to the client, so if you are also attempting to send a response from some other part of the code then you will be attempting to send two sets of responses, resulting in that error message.

Techyrack Website stock market day trading and youtube monetization and adsense Approval

Adsense Arbitrage website traffic Get Adsense Approval Google Adsense Earnings Traffic Arbitrage YouTube Monetization YouTube Monetization, Watchtime and Subscribers Ready Monetized Autoblog



from Web Development – My Blog https://www.techyrack.com/syndication/2022/09/05/foreach-not-working-as-expected-in-nodejs-javascript-sitepoint/
via IFTTT

No comments:

Post a Comment