Testing a simple GET request from NodeJS - node.js

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');

Related

How can I make an incredibly simple node.js server which itself makes an HTTP request?

I have found very simple code that creates a server and displays a string, using the "http" module.
eg. from https://garywoodfine.com/simple-lightweight-nodejs-webserver/:
var http = require('http');
var server = http.createServer(function (req, res) {
var body = 'Amazing lightweight webserver using node.js\n';
var content_length = body.length;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain' });
res.end(body);
});
server.listen(3939);
console.log('Server is running on port 3939');
I have found very simple code that gets data over HTTP, using the "got" module.
eg. from https://nodesource.com/blog/express-going-into-maintenance-mode:
const got = require('got');
(async () => {
try {
const response = await got('https://www.nodesource.com/');
console.log(response.body);
//=> '<!doctype html> ...'
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
})();
However I am failing to integrate the two to create a server that, when visited, makes the HTTP call and returns the result. I essentially just want to replace the var body = 'Amazing lightweight webserver using node.js\n'; line from the Gary Woodfine example with the output of the Nodesource example.
I'm not particularly looking for comments or questions as to why I would want to make something that does this, I'm trying to understand fundamentally why I can't just do what feels like a very simple and natural thing to do: return content based on a server side request to another web service. I get the impression that the issue is to do with the asynchronous paradigm and obviously I understand the performance improvements it offers, I'm failing to understand how you structure something that works for this simple usecase.
With thanks to Brad for his comment, I now have code that integrates the two samples:
var http = require('http');
const got = require('got');
var server = http.createServer(function (req, res) {
var body = (async () => {
try {
const response = await got('https://www.nodesource.com/');
var body = response.body;
var content_length = body.length;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain' });
res.end(body);
//=> '<!doctype html> ...'
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
})();
});
server.listen(3939);
console.log('Server is running on port 3939');
This code can be stripped down further obviously, to the sort of level of simplicity I had in mind.
Where I was going wrong was by trying to handle all the http response code after the async block, when I needed to do it inside it.

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);
});
});

node.js - end the request immediately?

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();
});

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