How to fix 'ERROR _HTTP_INVALID_STATUS_CODE' in Node? - javascript

I got some error and I have no Idea what does It mean any ideas, please?
This is the error:
I have no idea what is going on because I never got the error like that before and I am using res.redirect same way as always. I found out that you should use res. render, but I want to be redirected to a page not to render the page...
> Sun, 10 Feb 2019 18:47:15 GMT express deprecated res.redirect(url,
> status): Use res.redirect(status, url) instead at
> routes\placeorder.js:50:17 RangeError [ERR_HTTP_INVALID_STATUS_CODE]:
> Invalid status code: [object Object]
> at ServerResponse.writeHead (_http_server.js:208:11)
> at ServerResponse.writeHead (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\on-headers\index.js:55:19)
> at ServerResponse.writeHead (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\on-headers\index.js:55:19)
> at ServerResponse._implicitHeader (_http_server.js:199:8)
> at write_ (_http_outgoing.js:585:9)
> at ServerResponse.write (_http_outgoing.js:567:10)
> at writetop (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\express-session\index.js:290:26)
> at ServerResponse.end (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\express-session\index.js:351:16)
> at ServerResponse.redirect (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\express\lib\response.js:947:10)
> at putOrderToDBAndRedirect (C:\Users\Petr\WebstormProjects\BakalarskaPrace\routes\placeorder.js:50:17)
> _http_server.js:208
> throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
> ^
>
> RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code:
> [object Object]
> at ServerResponse.writeHead (_http_server.js:208:11)
> at ServerResponse.writeHead (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\on-headers\index.js:55:19)
> at ServerResponse.writeHead (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\on-headers\index.js:55:19)
> at ServerResponse._implicitHeader (_http_server.js:199:8)
> at write_ (_http_outgoing.js:585:9)
> at ServerResponse.end (_http_outgoing.js:709:5)
> at writeend (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\express-session\index.js:261:22)
> at Immediate.ontouch (C:\Users\Petr\WebstormProjects\BakalarskaPrace\node_modules\express-session\index.js:348:11)
> at processImmediate (timers.js:632:19)
>
> Process finished with exit code 1
const putOrderToDBAndRedirect = async(res,userId,serviceObj,
ordStart,ordEnd) =>{
try{
const result = await pool.query('SELECT id ' +
'FROM orders ' +
'WHERE ($1,$2) OVERLAPS (ord_start,ord_end)',
[ordStart,ordEnd]);
if(isOverlaping(result)){
console.log('redirect to page with orders');
res.redirect('/objednat')
}else{
await pool.query('INSERT INTO orders (ord_entered,ord_start,user_id,service_id,ord_end)' +
' VALUES($1,$2,$3,$4,$5)',
[new Date(),ordStart,userId,serviceObj.id,ordEnd]);
const resultArr = await pool.query('SELECT firstname,lastname,phonenumber ' +
'FROM users ' +
'WHERE ' +
'id = $1',[userId]);
console.log(resultArr.rows[0]);
const obj = constructOrderObj(serviceObj,ordStart,resultArr.rows[0]);
res.redirect('/objednano',{orderObj:obj});
}
}catch(err){
console.error(err);
}
};

You're calling res.redirect('/objednano',{orderObj:obj}); but that does not match the function signature for res.redirect() which takes an optional status as the first argument and the path as the second argument (or the path as the first argument if there is only one argument, in which case status will default to 302).
It's unclear to me what you're trying to do there, to be honest. But that line is the problem. It's treating the first argument as the status code, and '/objednano' is obviously an invalid HTTP status. So the error message is complaining that the HTTP status is invalid.

If you use res.redirect to send the response to the client, it will have a status code of 302 (which basically is a redirect) means that the the current data that you need is not available in the current location, but in another location as redirected
If you are trying to get this resource from a frontend app or client (like using fetch or XMLHTTPresponse, then you might get such an error)
The best possible way is to explicitly tell express (or the response object) that you are trying to send a json response for this request

Related

Error while sending message (whatsapp-web.js)

I am trying to send a message by using whatsapp web.js I dont know why I am facing the error.
app.post("/send",(req,res)=>{
const numbersBox = req.body.mobiles;
const numbers = numbersBox.split(",")
// loop through all the numbers and send message to each number.
numbers.forEach(async eachNumber=>{
const sanitized_number = eachNumber.toString().replace(/[- )(]/g, ""); // remove unnecessary chars from the number
const final_number = `91${sanitized_number.substring(sanitized_number.length - 10)}`; // add 91(india code) before the number
const number_details = await client.getNumberId(final_number); // get mobile number details
if (number_details) {
const sendMessageData = await client.sendMessage(final_number, req.body.message); // send message
} else {
console.log(final_number, "Mobile number is not registered");
}
})
})
When I tried to send messages without using forEach loop and sending message to single user it got succeeded but now it is showing below error
throw new Error('Evaluation failed: ' + helper_js_1.helper.getExceptionMessage(exceptionDetails));
^
Error: Evaluation failed: Error: wid error: invalid wid
at new c (https://web.whatsapp.com/app.c5b22a78d334f432a3c8.js:68:44944)
at Object.s [as createWid] (https://web.whatsapp.com/app.c5b22a78d334f432a3c8.js:68:50062)
at __puppeteer_evaluation_script__:2:53
at ExecutionContext._evaluateInternal (C:\Users\prudh\OneDrive\Documents\projects\whatsapp\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:221:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ExecutionContext.evaluate (C:\Users\prudh\OneDrive\Documents\projects\whatsapp\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:110:16)
at async Client.sendMessage (C:\Users\prudh\OneDrive\Documents\projects\whatsapp\node_modules\whatsapp-web.js\src\Client.js:686:28)
at async C:\Users\prudh\OneDrive\Documents\projects\whatsapp\index.js:57:37
are you adding the "#c.us" at the end of the numbers? Every contact id should be like "5958978454#c.us" to consider it a valid number

Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0

I have made a small vanilla javascript code to fetch api but it is throwing the error "Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0". I m not able to understand, exactly why the error is caught. Can somebody help me to resolve this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
.then(function(response) {
return response.json();
})
.then(function(apiResponse) {
// Output API response to console to view.
console.log(apiResponse);
});
It's because of this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
It should be,
const config = {
url: "https://randomuser.me/api/",
numberCards: 24
};
fetch(`${config.url}?amount=${config.numberCards}`)
It's because the json data are from "https://randomuser.me/api/". Not "https://randomuser.me/". And the query strings must begin with a "?" mark. "&" mark is used to separate query strings. (like this "https://example.com/?amount=24&hi=en")

SyntaxError: Unexpected token v in JSON at position 2

I am running a node.js server running express.js on my local machine and need to decode a request made by the client, that contains a json string in it. I run the code below and get the following error.
SyntaxError: Unexpected token v in JSON at position 2
at JSON.parse (<anonymous>)
at C:\myLocation\source\repos\server\server\server.js:144:19
at Layer.handle [as handle_request] (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\index.js:317:13)
My request is
http://localhost:1337/%7B%22Code%22:%22VNdVwY9iWhFZ114CjcDZbY%22,%22Chat%22:%22Test.txt%22%7D
The expected json is
{"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
I get the json, but it still gives me the same error.
My code:
app.use(function (req, res) {
//console.log(req.url)
var myStr = req.url.replace('/', '')
if (myStr != false) {
let decodeStr = decodeURIComponent(myStr)
var test = JSON.parse(decodeStr)
var json = JSON.stringify(test)
if (json.includes(createkey)) {
console.log("Create: " + json)
createFile(req, res, test)
} else if (json.includes(modKey)) {
console.log("Modify: " + json)
modifyFile(req, res, test)
} else if (json.includes(readFileKey)) {
console.log("Read: " + json)
readFile(req, res, test)
}
} else {
res.sendStatus(404)
console.log("home")
}
})
Why do I get the error?
Edit 1
I added console.log(decodeStr)but I still get the error. It returns {"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
{"Code":"'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"} is not a valid json, that's why you encounter that error,
The other way around, you could parse
JSON.parse('{"Code":"\'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"}')
Try
var uri = "http://localhost:1337/%7B%22Code%22:%22%5C'GAHGAaphgAP:gjpaGHAHAG%7BAaGRAP;GHPG;RA%22,%22Chat%22:%22Test.txt%22%7D";

Why is my (try-catch) code executed too soon in NodeJS?

On the response of an HTTP GET call (with native http module), I try toJSON.parse() the response after the end event is emitted. I know for sure the the data i'm getting is valid JSON but still the JSON.parse throw an error. And my logs indicate that the JSON.parse is invoked before it should.
res.on("end", () => {
console.log('Req ended message is', body);
try {
var passport = JSON.parse(body);
} catch (e) {
w.info(
"Cannot parse the response from : " +
process.env.mongo_api_host +
" | error : " +
e
);
}
callback(passport);
return;
});
And my log shows :
info: Getting MongoDB passport for model : CESI
info: Cannot parse the response from : mongo_api | error : SyntaxError: Unexpected end of JSON input
info: Req ended message is *long valid JSON data*
We can clearly see in the logs that the parse error is caught and logged before the "Req ended message is : ... stuff".
What am I missing ?
Edit 1 :
Even by putting callback(passport) inside try block as suggested in comment it still does it :
res.on("end", () => {
try {
console.log("Req ended message is", body);
var passport = JSON.parse(body);
//TODO What if you get an array ?
if (passport._id) delete passport._id;
callback(passport);
} catch (e) {
w.info(
"Cannot parse the response from : " +
process.env.mongo_api_host +
" | error : " +
e
);
}
return;
});

Error: Can't set headers after they are sent. comes from calling the smart contract function

I wrote a smart contract for creating simple database. It contains multiple functions , when i hit an REST api first time it gives me correct output but at further hits it make node server crash with a message --
F:\project\blockchain\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module
.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=type
of process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(EN
VIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write
(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath"normalize";var ret=nodeFS["readFileSync"](file
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (F:\project\blockchain\node_modules\express\lib\response.js:725:10)
at ServerResponse.send (F:\project\blockchain\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (F:\project\blockchain\node_modules\express\lib\response.js:256:15)
at F:\project\blockchain\BlockchainDB\users\userFunction.js:37:47
at F:\project\blockchain\node_modules\web3\lib\web3\filter.js:120:21
at Array.forEach (native)
at F:\project\blockchain\node_modules\web3\lib\web3\filter.js:119:32
at Array.forEach (native)
at Object.onMessage [as callback] (F:\project\blockchain\node_modules\web3\lib\web3\filter.js:117:22)
my code for api
module.exports.creation=function(req,res){
var user_id = req.params.user_id || req.body.user_id;
var currency = req.params.user_id || req.body.currency ;
if(user_id == undefined || currency == undefined){
res.status(500).json({status:false,errors:"Empty parameters"});
}else{
isaccount().then(function(accountNumber){
if(accountNumber!=null){
var timestamp = Date.now();
var result = contract.createUser.sendTransaction(user_id,currency,accountNumber,timestamp,{from:web3.eth.coinbase,gas:600000});
var event = contract.CreatedUser(function(error, result) {
if (!error){
if(result.args.userId!= undefined && result.args.accountId!= undefined && result.args.categoryId!= undefined){
logger.info("user created with id :"+result);
res.status(200).json({status:true,data:{iduser:result.args.userId,accountId:result.args.accountId,created_at:timestamp}});
}else{
logger.info("user creation have problem :");
res.status(500).json({status:false,errors:"no response"});
}
}else{
logger.error(error);
res.status(500).send(false);
}
});
}else{
logger.debug("Problem in accountNumber generation");
res.status(500).send(false);
}
});
}
}
please help me to solve this problem
Thanks in advance
Try using return statement for all the res.status() calls. So, even though once the response status gets set to something, it is again getting res.status() somewhere after it.

Categories