Are responses to HTTP requests required? - node.js

I think it's a generally applicable question, but this is what I'm trying to do: small Node.JS app that receives a POST request from GroupMe whenever a message is posted in a group to trigger and fulfills a completely separate action. They state that the callback URL will receive an HTTP POST request from us every time a message is published to that group. It doesn't make much of a difference to me if I need to respond to the POST, but I was curious if it's even necessary or if it had any negative implications.
var server = http.createServer(function(request, response) {
doStuff(request);
});

It really depends what you're doing, but generally if no response is sent then applications or users which expect there to be one will wait until the connection times out, which may take up to a minute or longer, get a time out error and assume your service doesn't work.
You don't have to send any text, just a HTTP response code will do. Have doStuff() return whether it was successful and send the appropriate code based on it:
var server = http.createServer(function(request, response) {
response.send(doStuff(request) ? 200 : 400);
});
200 means OK, 400 means Bad Request

What I know in the field of HTTP request and response, You should at least say response.end().
If you won't say response.end client will be waiting for response. So better to say a response.end after tour task.
var server = http.createServer(function(request, response) {
doStuff(request);
response.end(); //It tells browser/client that server has finished it's work on this request.
});

Related

NodeJS http request event listener firing more than once

I'm new to backend development so have just made my first server using NodeJS and the http module. This is my code so far:
const http = require("http");
let count = 0;
const server = http.createServer((req, res) => {
res.write(count.toString());
//tells the server that all of the headers and body have been sent, so the message is complete
res.end();
count += 1;
});
server.listen(3000);
I understand how almost all of this code works. However, whenever I refresh the page on my local environment (send a new request) I would expect the displayed response to increment by 1, however, it increments by 2. The only reason I can think this would happen is that the request event listener is being fired twice on each page reload, however, I cannot find anything to help me with this issue so any help would greatly be appreciated.
If i understand what this website says https://www.w3schools.com/nodejs/met_http_createserver.asp
The requestListener is called every time a request is sent to the server.
You can check in your Navigator console (in the Network sub-tab) the different requests sent to your server.
Maybe there are multiple requests sent to your server on page reload.
I hope this helped, otherwise, you can try to log in your requestListener the req object to know what triggers it, and where does it come from.

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.

How does node.js handle simultaneous http requests?

I am learning node.js, and I am not managing to find a direct answer to this question. How does node.js deal with HTTP incoming requests, if they come in virtually at the same time? Let's say that one HTTP request comes in at a given time. As a result, the value of a global variable might change. However, at virtually the same time, another request comes in. In order to service the new request, the value of that one global variable is needed, but the code for the first request is still executing. How does node react to this?
Node.js processes the request one after the other. There is only one thread.
However, if you for example query the database for some information and pass a callback, while the query is executed, node.js can process new requests. Once the database query is completed, node.js calls the callback and finishes processing the first request.
EDIT:
Simple server example:
var http = require('http');
var numresponses = 0;
http.createServer(function (request, response) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is response #' + (++numresponses));
}).listen(80);
this server will always print out the number of the request even if two requests happen simultaneously, node will choose one that gets processed first, and both will have different numbers.

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.

node.js wait for response

I have a very limited knowledge about node and nob-blocking IO so forgive me if my question is too naive.
In order to return needed information in response body, I need to
Make a call to 3rd party API
Wait for response
Add some modifications and return JSON response with the information I got from API.
My question is.. how can I wait for response? Or is it possible to send the information to the client only when I received response from API (as far as I know, connection should be bidirectional in this case which means I won't be able to do so using HTTP).
And yet another question. If one request waits for response from API, does this mean than other users will be forced to wait too (since node is single-threaded) until I increase numbers of threads/processes from 1 to N?
You pass a callback to the function which calls the service. If the service is a database, for example:
db.connect(host, callback);
And somewhere else in the code:
var callback = function(err, dbObject) {
// The connection was made, it's safe to handle the code here
console.log(dbObject.status);
res.json(jsonObject, 200)
};
Or you can use anonymous functions, so:
db.connect(host, function(err, dbObject) {
// The connection was made, it's safe to handle the code here
console.log(dbObject.status);
res.json(jsonObject, 200)
});
Between the call and the callback, node handles other clients / connections freely, "non-blocking".
This type of situation is exactly what node was designed to solve. Once you receive the request from your client, you can make a http request, which should take a callback parameter. This will call your callback function when the request is done, but node can do other work (including serving other clients) while you are waiting for the response. Once the request is done, you can have your code return the response to the client that is still waiting.
The amount of memory and CPU used by the node process will increase as additional clients connect to it, but only one process is needed to handle many simultaneous clients.
Node focuses on doing slow I/O asynchronously, so that the application code can start a task, and then have code start executing again after the I/O has completed.
An typical example might make it clear. We make a call to the FB API. When we get a response, we modify it and then send JSON to the user.
var express = require('express');
var fb = require('facebook-js');
app.get('/user', function(req, res){
fb.apiCall('GET', '/me/', {access_token: access_token}, function(error, response, body){ // access FB API
// when FB responds this part of the code will execute
if (error){
throw new Error('Error getting user information');
}
body.platform = 'Facebook' // modify the Facebook response, available as JSON in body
res.json(body); // send the response to client
});
});

Resources