throw new RangeError node js - node.js

I'm trying to work with IBM Watson Conversation service with Node.js.
I use 'express' to post a message:
app.post( '/api/message', function(req, res) {
}
and to print the message got from the service:
conversation.message( payload, function(err, data) {
if ( err ) {
return res.status( err.code || 500 ).json( err );
}
return res.json( updateMessage( payload, data ) );
} );
I just ran the application on port 3000. While the page is not loaded and I got this error:
_http_server.js:192
throw new RangeError(`Invalid status code: ${statusCode}`);
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:573:10)
at ServerResponse.send (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:204:10)
at ServerResponse.json (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:249:15)
at C:\IBM\1.Mission\2016\conversation-simple-master(1)\conversation-simple-m
aster\app.js:86:44
at Request._callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\co
nversation-simple-master\node_modules\watson-developer-cloud\lib\requestwrapper.
js:47:7)
at self.callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\conver
sation-simple-master\node_modules\watson-developer-cloud\node_modules\request\re
quest.js:200:22)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
I don't think the problem is from npm, back my package... While it seems a generic problem...Thanks for you help.

Request to IBM Watson Conversation service probably ended with error with code "0" and it isn't a valid HTTP status code. This should work:
conversation.message(payload, function(err, data) {
if (err) {
return res.status(500).json(err);
}
return res.json(updateMessage(payload, data));
});

Related

node reciving an unhandled error event need some insite?

I've searched Hi and Low through web sites and docs, and I've yet to figure out why Im getting this error. Yes I'm new to node. I thought id ask here as a last resort.
the error I'm receiving is:
events.js:292
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:668:15)
at ServerResponse.end (_http_outgoing.js:789:7)
at Server.<anonymous> (/mnt/sdc/opt/codeWork/ReactBuilds/be_full-stack/app.js:10:9)
at Server.emit (events.js:315:20)
at parserOnIncoming (_http_server.js:874:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:727:7)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Here's my code I'm running node v14.16.0
const http = require('http')
const server = http.createServer((req, res)=>{
if(req.url === '/') {
res.end('Welcome to our home page')
}
if(req.url === '/about') {
res.end('Here is our short history')
}
res.end(`
<h1>Ooops</h1>
<p>This is not the page you are looking for</p>
backHome
`)
})
server.listen(5000)
any incites are very welcome
Thanks
You should introduce early returns in your code so that you don't call res.end multiple times when one of the conditions evaluates to true with your request handler still handling 404:
const server = http.createServer((req, res) => {
if (req.url === "/") {
return res.end("Welcome to our home page");
}
if (req.url === "/about") {
return res.end("Here is our short history");
}
res.end(`
<h1>Ooops</h1>
<p>This is not the page you are looking for</p>
backHome
`);
});

Google Cloud Function - Storage - Delete Image - "ApiError: Error during request"

UPDATED QUESTION
The problem is ApiError: Error during request.
Code:
import * as functions from 'firebase-functions';
const cors = require('cors')({ origin: true });
import * as admin from 'firebase-admin';
const gcs = admin.storage();
export const deleteImage = functions.https.onRequest((req, res) => {
return cors(req, res, async () => {
res.set('Content-Type', 'application/json');
const id = req.body.id;
const name = req.body.name;
const imageRef = gcs.bucket(`images/${name}`);
if (!name || !id) {
return res.status(400).send({message: 'Missing parameters :/'});
}
try {
await imageRef.delete();
console.log('Image deleted from Storage');
return res.status(200).send({status: 200, message: `Thank you for id ${id}`});
}
catch (error) {
console.log('error: ', error);
return res.status(500).send({message: `Image deletion failed: ${error}`});
}
});
});
And the problem is here: await imageRef.delete();, I get the following error:
ApiError: Error during request.
I do, indeed, have admin.initializeApp(); in one of my other functions, so that can't be the issue, unless GCF have a bug.
More In-Depth Error:
{ ApiError: Error during request.
at Object.parseHttpRespBody (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:187:32)
at Object.handleResp (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:131:18)
at /user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:496:12
at Request.onResponse [as _callback] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/node_modules/retry-request/index.js:198:7)
at Request.self.callback (/user_code/node_modules/firebase-admin/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/firebase-admin/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: undefined,
errors: undefined,
response: undefined,
message: 'Error during request.' }
(old question removed)
"Error: Can't set headers after they are sent" means that you tried to send two responses to the client. This isn't valid - you can send only one response.
Your code is clearly sending two 200 type responses to the client in the event that imageRef.delete() fails and the catch callback on it is triggered.
Also, you're mixing up await with then/catch. They're not meant to be used together. You choose one or the other. Typically, if you're using await for async programming, you don't also use then/catch with the same promise. This is more idiomatic use of await with error handling:
try {
await imageRef.delete()
res.status(200).send({status: 200, message: `Thank you for id ${id}`});
} catch (error) {
res.status(500).send({message: `Image deletion failed: ${err}`});
}
Note also that you typically send a 500 response to the client on failure, not 200, which indicates success.

Node server is getting down with Error: write after end

We are streaming files from s3, its running well but sometime (randomly in few days) its gives error and node instance is getting down. our code is
s3Utils.headObject(assetId, function (err, metadata) {
if (err && err.code === 'NotFound') {
console.log("file not found on s3: ", assetId) ;
res.send({"success":false, "message":"file not found on s3: "+ assetId});
} else {
var download_file_name = assetId;
if(metadata.Metadata && metadata.Metadata.filename) {
download_file_name = metadata.Metadata.filename;
}
if(metadata.ContentLength) {
res.setHeader('Content-Length',metadata.ContentLength);
}
res.setHeader('Content-disposition', 'attachment; filename=' +download_file_name);
res.attachment(download_file_name);
var fileStream = s3Utils.getObjectAsReadStream(assetId);
fileStream.pipe(res);
}
});
we are getting below error in logs
events.js:154
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (_stream_writable.js:166:12)
at PassThrough.Writable.write (_stream_writable.js:211:5)
at IncomingMessage.ondata (_stream_readable.js:536:20)
at emitOne (events.js:90:13)
at IncomingMessage.emit (events.js:182:7)
at IncomingMessage.Readable.read (_stream_readable.js:368:10)
at flow (_stream_readable.js:751:26)
at resume_ (_stream_readable.js:731:3)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
Server is getting down after this error.
Please suggest.

Alternative to waiting for child_process to quit node.js

I've got these 2 codes running in 1 script:
The ping script:
app.get("/ping", function(req, res) {
res.send("Pong!");
});
And a work in progress youtube downloader:
app.post("/nodedl", function(req, res) {
res.write("===Gradyncore listnener===\n")
res.write("Recived POST request from "+req.ip+" to /nodedl\n")
res.write("POST(url): "+req.body.url+"\n")
res.write("checking key...\n")
if (req.body.key==="<Insert key here>"){
res.write("Key is valid! Skipping pre-download script...\n")
} else {
res.write("Key is invalid. Running pre-download script...\n")
exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function (error, results) {
if (results != null) {
res.write(results+"\n");
} else if (error != null) {
res.write("Error: " + error+"\n");
}
});
}
res.end();
});
The problem is, by the time check.sh finishes, res.end(); has allredy been emitted, causing this error followed by a crash
events.js:160
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
at /home/gradyn/listener/app.js:29:13
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
I'm fairly new to node.js, but from what I understand, If i wait for the child process to complete before calling res.end(), the entire script (including the ping listener) will not work until the child process completes.
How should I go about doing this?
Problem is that your exec is asynchronous, code below it won't wait to for completion of exec and get executed... You have to end response inside callback function:
app.post("/nodedl", function(req, res) {
res.write("===Gradyncore listnener===\n")
res.write("Recived POST request from "+req.ip+" to /nodedl\n")
res.write("POST(url): "+req.body.url+"\n")
res.write("checking key...\n")
if (req.body.key==="<Insert key here>"){
res.write("Key is valid! Skipping pre-download script...\n")
} else {
res.write("Key is invalid. Running pre-download script...\n")
exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function(error, results) {
if (results != null) {
res.write(results+"\n");
res.end();
} else if (error != null) {
res.write("Error: " + error+"\n");
res.end();
}
});
}
});

Node.js Error: Max redirects exceeded

how I can ignore pages with cycle redirects?
I use this code to fetching pages:
var libxml = require("libxmljs"),
http = require('follow-redirects').http,
url = require("url");
var request = http.request( { "host": host, "path": URL, "port": 80 }, function( response ) {
var str = '';
response.on( 'data', function( chunk ) {
str += chunk;
});
response.on( 'end', function() {
callback( str, response.statusCode );
}).on( 'error', function ( err ) {
console.log( err );
});
}).end();
It will not go to 'error' block, and I've got an exception:
events.js:85
throw er; // Unhandled 'error' event
^
Error: Max redirects exceeded.
at ClientRequest.cb (/var/parsing/node_modules/follow-redirects/create.js:55:19)
at ClientRequest.g (events.js:199:16)
at ClientRequest.emit (events.js:107:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:426:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_client.js:317:20)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
The error is being thrown by the request object, not the response object, so you need to add an (additional) error listener to request;
var request = http.request(...).on('error', function(err) {
...
}).end();
Looking at the docs for the package you are using (https://www.npmjs.com/package/follow-redirects), it looks like it just has a maxRedirects option. Directly from the linked page:
require('follow-redirects').maxRedirects = 10; // Has global affect (be careful!)
https.request({
host: 'bitly.com',
path: '/UHfDGO',
maxRedirects: 3 // per request setting
}, function (res) {/* ... */});

Resources