express response with a callback - node.js

Is it possible to send a response from express, and wait for a return response before continuing?
A typical scenario is something like this
Server A sends a request to server B.
Server B processes the request and sends to back to server A
Server B waits for a response from server A before continuing
Server A does further processing of the response from Server B and sends it back to Server B
Server B then handles the rest of the processing required.
My understanding is that normally this is handled with callbacks. In express I would expect to do something like
res.write('response', callback);
function callback() {
//do stuff
}
I don't see that this is possible with the res.write method though. Is there another method I can use with express to get this functionality? I've never used socket.io before, but this seems like a scenario where websockets would be useful. Am I wrong in this assumption?

res.on('finish', callback);
is sent when the last of the data is given to the OS to deal with.
http://nodejs.org/api/http.html#http_event_finish
If you need to know when the client receives/processes the data, however, the client must send something back to the server, in which case socket.io could help.

I appreciate all the responses and help from everyone, I ended up using sessions to get what I needed.
var session = require('express-session');
Thanks again

Related

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 to wait for a response from the client while making a request?

This is the flow:
I send a request to my server: GET /status/
My server sends a push notification to my client
My client - after a slight delay(up to 10
seconds) - makes a request to my server with the status: POST
/status/XYZ
Now the request i started on step 1, should return XYZ
My server is node.js and i'm using express for routing. Any ideas how can i achieve something like this? My idea was to store the status in my database in step 3, and query my db every second in step 1 until i have the status, but i'm pretty sure this is not a good solution.
Status in real time? You should use sockets for that. Have a look at socket.io
Still want to use HTTP(s) requests?
Simply store the result of the first request into an object inside (or outside) the database (it would act as a cache layer). So when he queries he can get that result straight away. Something like:
{
ABC: value
XYZ: value,
}
router.post('status/XYZ', (req, res) => {
return res.json(values['XYZ']);
});

Mixing POST request with websocket response - is it a bad practice?

Here is a short snippet of node.js code (express.js and socket.io). Could sending POST requests and emitting socket responces be considered as a bad practice and why?E.g.:
var io = require('socket.io')(http);
app.post('/tickets', jsonParser, function(req, res) {
io.emit('ticket', req.body);
return res.sendStatus(200);
}
I see no problem with that. I actually created a notification system that receives the message and destination as a post and sends notifications to multiple sockets like that.
From your code it looks like that's what your are doing, someone creates a ticket and you send a notification to all listeners.
That seems to be the most practical way and added bonus of being a proper api for use with external server like php or .net. If you're just using it from your own node app than perhaps you could just make it a socket event instead unless you are planning on getting requests from outside your app.

Routing with socket.io

I'm writing an express app.js with socket.io, and came across a problem.
I can't figure out how to use the routes.
I want the client to write for example localhost:3000/?id=3 and get something according to the id.
But in the socket.io connection event I dont know the url or the params (or is there a way?)
io.on('connection', function (socket) {/*should be something according to the id in the url*/});
untill now I just checked the id with
app.get('/', function (req, res) {
//req.query.id
});
Anyone knows a way around this?
Thank you!
It appears you may be a bit confused about how you use webSockets. If you want to make an http request such as localhost:3000/?id=3, then you don't use webSockets. You use the normal routing mechanisms in Express.
A webSocket connection is created and then persists. From then on, you define messages with optional data as arguments for those messages and you can send these messages either direction on the webSocket. webSocket messages are sent on an existing webSocket, not to a URL. You could create a message for sending URLs from client to server if you wanted. If that was the case, you could do this in the client:
socket.emit("sendURL", url);
And, then you would listen for the "sendURL" message on the server.

Get a static request to push some data to clients using Node.js and Socket.io

I'm new to Node.js, and I've been playing with the "chat" example provided with the Socket.io install package. Is shows in a few lines of code how you can push some data to several clients (browsers) in a push-fashion (no pulling).
Here is the code on the server side : http://pastie.org/1537175
I get how you can send a message to a client with client.broadcast(msg), but I don't get how you can do it outside of the
io.on('connection', function(client){
... }
loop
I would like to invoke a client.broadcast(msg) when someone hits a particular url (like '/test.html'), see line #32. The device asking for the '/test.html' is not a typical "ajax-enabled" browser, but a mere text-based browser, so I cannot initialize an asynchronous request with the server. Any idea?
Thank you.
you can use .broadcast on your io object
case '/test.html':
io.broadcast('test'); // This is where I would like to invoke a client.broadcast(msg);
break;

Resources