node.js - end the request immediately? - node.js

So I have the following code -
var http = require('http');
http.createServer(function (req, res) {
console.log("Connected!");
res.writeHead(200);
req.on('data', function(data) {
res.write(data);
});
}).listen(5000);
But when I write into chrome localhost:5000 it just load the page, and then it says that the server didn't sent any data..
I figured out that If I write req.end(); after the data event, it loads the page perfectly. However, I don't want to end the request immediately.
What should I do?

You'll have to call res.end() at some point, but you can wait for the req to 'end' first:
req.on('end', function () {
res.end();
});

Related

Edit the response after a redirect (node.js & express)

I have a Nodejs express app which receives POST requests (XML) and simply redirects them to a different host replying to the original caller (also with an XML message).
var app = require('express')();
app.post('/', function(req, res) {
res.redirect(307, 'http://localhost:8888/');
});
app.listen(3000, function() {
console.log('Application listening on http://localhost:3000/');
});
What I am trying to achieve is to modify the response from the second host (localhost:8888). How do I intercept and edit the response from the second host before it reaches the original caller?
I cannot figure it out from the documentation so any help would be very appreciated, thank you.
You cannot do that as the response from server 2 is fetched by the client handling the redirect (e.g. your browser). You have to fetch the response yourself in the server side, modify it and send it back.
var app = require('express')();
var request = // your preferred http library
app.post('/', function(req, res) {
request.get('http://localhost:8888/', function (err, response) {
if (err) {
return res.error(err);
}
// Here you have the response, you can modify it.
res.send(response.body);
});
});
app.listen(3000, function() {
console.log('Application listening on http://localhost:3000/');
});

Testing a simple GET request from NodeJS

For testing purpose,I want to call a method (that does GET request) as soon as the server is created. I have the below code.
var rp = require('request-promise');
var http = require('http');
var URLSplunk = MY_URL
var headersSplunk = {
'Authorization': 'Bearer MY_AUTH',
'Cache-Control': 'no-cache',
'X-Requested-By': 'BABEL_FISH',
'client': 'slack'
};
function testSplunk(){
var optionsSplunk = {
url: URLSplunk,
headers: headersSplunk,
json: true
};
rp(optionsSplunk)
.then(function (resultReply) {
console.log("Splunk GET success")
console.log(resultReply)
})
.catch(function (error) {
console.log(`Error: \n${error}`);
});
}
http.createServer(function (request, response) {
testSplunk()
}).listen(3000);
console.log('Server started');
I was expecting to see the GET result or error but I only see 'Server started' message.
What am I missing?
My comment echo'd in greater detail by #jfiend00.
The way you have the code now, your testSplunk() function will get called only when your http server gets a request. It's inside the http server requestListener callback. So, you have to send the http server a request to trigger that callback so the testSplunk() function gets called.
The testSplunt() function is never being called by the program until a request is made to the server.
Putting it after the requestListener callback will allow for it to be executed in the manner that you want it to be.
E.g.
http.createServer(function (request, response) {
//This function is called when the server gets a request
//Process request.......
}).listen(3000);
testSplunk();
console.log('Server started');

Want to write capture and re-transmit http/https request to Browser?

I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});

how to send reponse when timeout in node.js http module

On nodejs.org socket.setTimeout, it says
When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.
But when I test code like this:
var http = require('http');
server = http.createServer(function (request, response) {
request.socket.setTimeout(500);
request.socket.on('timeout', function () {
response.writeHead(200, {'content-type': 'text/html'});
response.end('hello world');
console.log('timeout');
});
});
server.listen(8080);
The socket is closed immediately after timeout, and no data is replied to the browser. Which is quite different from the document. Is this a bug or is there any tricks dealing socket under http module?
The documentation is indeed correct, however it looks like the http module adds a 'timeout' listener which calls socket.destroy(). So what you need to do is get rid of that listener by calling request.socket.removeAllListeners('timeout').
So your code should look like:
var http = require('http');
server = http.createServer(function (request, response) {
request.socket.setTimeout(500);
request.socket.removeAllListeners('timeout');
request.socket.on('timeout', function () {
response.writeHead(200, {'content-type': 'text/html'});
response.end('hello world');
console.log('timeout');
});
});
server.listen(8080);

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.
var server = http.createServer(function(req, res)
{
var body = "";
req.on("data", function(chunk)
{
body += chunk.toString();
});
req.on("end", function() {
var rtn = obj.AddonPostMethod(filepath,body);
if(rtn.length < 13)
{
res.writeHead(201, {"Location" : rtn});
res.end();
}
else
{
res.writeHead(400, {"Content-Type" : application/json"});
res.write(''+rtn);
res.end();
}
});
}});
The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.
I don't think you're actually listening on a port with the code you reference.
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
You never declare the http object as actually listening on a port/ip with the .listen() function.
Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.
var server = http.createServer();
server.listen(8000);
server.on('request', function(req,res){ /* do something with the request */ });
More documentation on the http object can be found on the node.js documents for http

Resources