When is Node http request actually fired? - node.js

Is node http request actually fired after req.end or after http.request ?
Context: I am using node js http module and wanted to understand what happens between:
var req = http.request(options)
// Register handler events
req.end();
Can node open socket and start dns look up before req.end() Or req.end() is to just suggest that no more data needs to be sent ?
From documentation "With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body." I am not sure what to make out of this ?

Is node http request actually fired after req.end or after http.request ?
http.request() returns an instance of the http.ClientRequest class and the ClientRequest instance is a writable stream. Therefore, the request will be fired after req.end()
Can node open socket and start dns look up before req.end() Or req.end() is to just suggest that no more data needs to be sent ?
The answer for your question is no, the socket will be created after you sent the request, as mentioned before when you use req.end().
From documentation "With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body." I am not sure what to make out of this ?
I think you should try to understand a little more about node streams. When you invoke the request method from http, it returns a writable stream, that means the request is "available" to be written. When you do the .end() you are telling to that stream that no more writing is needed, in other words, you don't need to build the request anymore and so the request is sent.

Related

Is there any workaround to send response until a promise is finished and send another response after it is finished in nodejs express

I have a promise call which takes a long time to return. So I need to send some response like "In progress" until the response is returned. Once it is returned , I need to send another response saying "Done".
I want this in Nodejs-Express App
How to do it?
Using SocketIO would be an option as you would maintain a stream of data open while it is required. But you go beyond of a simple http Express server ...

what happens if neither res.send() nor res.end() is called in express.js?

I have a security issue that someone is trying to call random APIs that are not supported on our server but are frequently used for administrators API in general. and I set this code below to handle 404 to not respond to this attack
url-not-found-handler.js
'use strict';
module.exports = function () {
//4XX - URLs not found
return ((req, res, next) => {
});
};
what happens to client is that it waits until the server responds but I want to know if this will affect the performance of my express.js server also what happens behind the scene in the server without res.send() or res.end() ?
According to the documentation of res.end().
Ends the response process. This method actually comes from Node core,
specifically the response.end() method of http.ServerResponse.
And then response.end
This method signals to the server that all of the response headers and
body have been sent; that server should consider this message
complete. The method, response.end(), MUST be called on each response.
If you leave your request hanging, the httpserver will surely keep data about it. Which means that if you let hang many requests, your memory will grow and reduce your server performance.
About the client, he's going to have to wait until he got a request timeout.
The best to do having a bad request is to immediately reject the request, which is freeing the memory allowed for the request.
You cannot prevent bad requests (maybe have a firewall blocking requests from certains IP address?). Best you can do is to handle them as fast as possible.

why subsequent HTTP requests

My JavaScript makes that ajax call which retrieves a JSON array.
I am trying simulate long running HTTP REST call request that takes longer to return the results.
The way I do it is delay writing anything to the response object on the server side until 5 minutes elapsed since the request landed. After that I set the status to 200 and write the response with the JSON ending the stream.
Putting a breakpoint on the serve side I realize that the request shows up second time but the browser's Network tab does not show another request being made.
It may not be relevant but I am using browsersync middlewars to serve this JSON and write the bytes and end the response in setTimeout().
setTimeout(()=> {
res.statusCode = 200;
res.write(data);
res.end();
});
Question:
Anyone has any explanation as to why this is happening ? And if there is a way to simulate this in another ways ?
In most cases the browser should retry if connection is closed before response. This is a link to the details => HTTP spec Client Behavior if Server Prematurely Closes Connection
BTW it might help you use the chrome throttling options on the network section of dev tools (F12)

Express.js send response before end of execution

In a Express application I would like to do something like this:
app.get('/some/route', someMiddleWare(), function(req, res){
var status = undefined;
if( /*someCondition*/ ) status = 200;
else status = 403
res.status(status).send('');
// do something else
})
In the first part I do something that is needed in order to decode what response to give, in the second (after send()) I do something additional that needs to be done in the same execution (i.e. not asynchronously) but does not really concern the user.
The question is: can I be sure that after send() returns the response is already on its way back to the user? Or is it sent only after the execution of my handler function?
Thanks
Yes. You're code will execute in the function even after you send the data through res.send().
However, after you use res.send() you will no longer be able to send any other data with that same response to that request.
The question is: can I be sure that after send() returns the response
is already on its way back to the user? Or is it sent only after the
execution of my handler function?
Yes, you can be sure the data is on its way. At the point you call res.send(), the data has been written to the underlying TCP infrastructure and it is then up to the TCP stack to send it. Due to TCP Nagle algorithm, there might be a short delay before the data is sent, but it will not be waiting for anything in your Express application. The data will be sent as soon as the TCP stack decides to send it.
It won't matter whether you are doing something else in the request handler after you send the response or not.
If you want to follow the actual source code for this, you first look at res.send(data) in express and that ultimately ends up calling res.end(data) in the http module. And, by looking at the http module, you can see that it is writing the data to the TCP implementation synchronously when it is called. There are no magic delays waiting for other things to happen in Express.

Connecting to a Reliable Webservice with Nodejs

My application needs to receive a result from Reliable Webservice. Here is the scenario:-
First I send a CreateSequence request. Then the server replies with a CreateSequenceResponse message. Next I send the actual request to the webservice.
Then the webservice send a response with 202 accept code and sends result in a later message. All these messages contain the header Connection: keep-alive.
I made request with http.ClientRequest. I could capture all responses except the result. http.ClientRequest fires only one response event.
How can I receive the message which contains the result?
Is there any way to listen to socket for remaining data (socket.on('data') did not work). I checked this with ReliableStockQuoteService shipped with Apache Synapse. I appreciate if someone can help me.
When you get the response event, you are given a single argument, which is an http.IncomingMessage, which is a Readable stream. This means that you should bind your application logic on the data event of the response object, not on the request itself.
req.on('response', function (res) {
res.on('data', console.log);
});
Edit: Here is a good article on how to make HTTP requests using Node.

Resources