My http.createserver in node.js doesn't work? - javascript

Hello guys i just started learning node.js today and search a lot off stuff on the internet , then try to code in node.js i use these two codes to show me the same result but the last one is show the error on my browser something likes "can not find the page".So please explain to me why?
// JScript source code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
This is working but
// Include http module.
var http = require("http");
// Create the server. Function passed as parameter is called on every request made.
// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
// Attach listener on end event.
// This event is called when client sent all data and is waiting for response.
request.on("end", function () {
// Write headers to the response.
// 200 is HTTP status code (this one means success)
// Second parameter holds header fields in object
// We are sending plain text, so Content-Type should be text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send data and end response.
response.end('Hello HTTP!');
});
}).listen(1337, "127.0.0.1");
This one is not working
Why?
The link of the last one that's not working
http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
Thank you for all the answers, but i still don't understand about the problems.
the last one that is not working just has request.on?

request is an instance of http.IncomingMessage, which implements the stream.Readable interface.
Documentation at http://nodejs.org/api/stream.html#stream_event_end says:
Event: 'end'
This event fires when no more data will be provided.
Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.
var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
console.log('there will be no more data.');
});
So in your case, because you don't use either read() or subscribe to the data event, the end event will never fire.
Adding
request.on("data",function() {}) // a noop
within the event listener would probably make the code work.
Note that using the request object as a stream is only necessary for when the HTTP request has a body. E.g. for PUT and POST requests. Otherwise you can consider the request to have finished already, and just send out the data.
If the code your posting is taken literally from some other site, it may be that this code example was based on Node 0.8. In Node 0.10, there have been changes in how streams work.
From http://blog.nodejs.org/2012/12/20/streams2/
WARNING: If you never add a 'data' event handler, or call resume(), then it'll sit in a paused state forever and never emit 'end'.
So the code you posted would have worked on Node 0.8.x, but does not in Node 0.10.x.

The function you are applying to the HTTP server is the requestListener which supplies two arguments, request, and response, which are respectively instances of http.IncomingMessage and http.ServerResponse.
The class http.IncomingMessage inherits the end event from the underlying readable stream. The readable stream is not in flowing mode, so the end event never fires, therefore causing the response to never be written. Since the response is already writable when the request handler is run, you can just directly write the response.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello HTTP!');
}).listen();

Related

node.js express: Is there a way to cancel http response in middleware?

I am writing a timeout middleware with express in node.js.
app.use((req, res, next) => {
res.setTimeout(3000, () => {
console.warn("Timeout - response end with 408")
res.status(408).json({ "error": "timeout 408" });
// !!! error will happen with next function when call like `res.send()`:
// Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
next()
})
If there's an endpoint that takes more than 3000 ms, my middleware will repsond with 408. However, the next function will respond again. I don't want to check if the response has been already sent by res.headersSent api every time.
Is there a better way to handle this - like the title said - to cancel the next response in the middleware?
It's your own code in the response handler that is still running (probably waiting for some asynchronous operation to complete). There is no way to tell the interpreter to stop running that code from outside that code. Javascript does not have that feature unless you put that code in a WorkerThread or a separate process (in which case you could kill that thread/process).
If you're just trying to suppress that warning when the code eventually tries to send its response (after the timeout response has already been sent), you could do something like this:
app.use((req, res, next) => {
res.setTimeout(3000, () => {
console.warn("Timeout - response end with 408")
res.status(408).json({ "error": "timeout 408" });
// to avoid warnings after a timeout sent,
// replace the send functions with no-ops
// for the rest of this particular response object's lifetime
res.json = res.send = res.sendFile = res.jsonP = res.end = res.sendStatus = function() {
return this;
}
});
next();
});

I want to know the meaning of this function(.on()) in detail

i dont know what is 'data' and req.on() method, please help me
http.createServer( (req, res) => { .....
if( req.method === 'POST') {
if( req.url ==='/user') {
let body ='';
req.on('data', (data) => {
body += data;
});
Basically a user can send data to an HTTP server by connecting to it, send the date and then disconnect. this works for a small amount of data. by this kind of request when the user sends an HTTP request and when http.createServer( (req, res) => {} gets called, you'll have a complete body and can access it in req.body, in other words, you've got the whole data sent by the user.
But sometimes the user wants to send a huge file(a big image, video, etc), the problem is, that it's problematic to send that huge data with a single request, instead, the user sends the data with a stream of data chunks. the user connects to the server and http.createServer( (req, res) => {} gets called, then the user starts to send the data in chunks, now with every chunk of data that is being sent and is being received by the server, req.on('data', (data) => {}) gets called, and it adds the received data to the body of the request. when the streams are finished, you'll have a complete body that contains that big file or any kind of big data that the user sent, and after finishing streams, the user disconnects from the server.
The req.on method is part of node's Event Emitter model. It provides methods to bind functions to certain events (on in this case) and ways to dispatch events to that functions
The data event is one of those examples. It is dispatched when there's data available in the buffer for the request to read, basically.
You can find more information on Event Emitters here and about the http events, you can find it here.
The req.on method is a function which allows to attach event listener for the event named which is passed as the first argument emitter.on.
the req object is type of http.ClientRequest which extends the EventEmitte which as some function which are related to Publish–subscribe pattern more.
in your case which i repeat bellow
req.on('data', (data) => {
body += data;
});
You are attaching a listener which will be executed every time the req object dispatch in their internal work flow the data event.

javascript synchronous asynchronous query [duplicate]

This question already has answers here:
I know that callback function runs asynchronously, but why?
(3 answers)
Closed 5 years ago.
I am new to Javascript.
Below nodejs code runs synchronously, I do not undestand, why?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
I got output as:
Server running at http://127.0.0.1:8081/
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
Below nodejs code runs asynchronously, I do not understand, why? I agree there is a callback in the readFile function, so why it behaves asynchronously?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
});
console.log("Program Ended");
Here is the output:
Server running at http://127.0.0.1:8081/
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Could you please someone explain me clearly why above is behaving like that. Are callbacks always asynchronous? I also would like to know how execution happens internally for callback functions.
Assume a control came to the line readFile function (which is having callback in it), so why does control immediately executes another statement? If control transers to another statement, who will execute callback function? After callback returns some value, does control again comes back to same statement ie., 'readFile' line?
Sorry for stupid query.
The synchronous version (fs.readFileSync) will block the execution until the file is read and return the result containing the file contents:
var data = fs.readFileSync('input.txt');
This means that the next line of code will not be executed until the file is completely read and the result returned to the data variable.
The asynchronous version on the other (fs.readFile) hand will immediately return the execution to the next line of code (which is console.log("Program Ended");):
fs.readFile('input.txt', function(err, data) {
// This callback will be executed at a later stage, when
// the file content is retrieved from disk into the "data" variable
console.log(data.toString());
});
Then later, when the file contents is completely read, the passed callback will be invoked and so you see the contents of the file printed at a later stage. The second approach is recommended because you are not blocking the execution of your code during the file I/O operation. This allows you to perform more operations at the same time, while the synchronous version will freeze any other execution until it fully completes (or fails).

Need help understanding Node.js in respect to routing using a JavaScript API?

I understand the basics of routing in Node.js and using the http module for it. I understand all the Node.js code below but just the JavaScript API part and how it is used to make the routing code much more cleaner is what I have trouble understanding. When I say "trouble understanding" I mean trouble understanding the syntax and how the routes object is used.
The code is from an E-book I have been learning from so please read the code below.
var http = require("http");
var url = require("url");
var route = {
routes : {},
for: function(path, handler){
this.routes[path] = handler;
}
};
route.for("/start", function(request, response){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello"); response.end();
});
route.for("/finish", function(request, response){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Goodbye");
response.end();
});
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
if(typeof route.routes[pathname] ==='function'){
route.routes[pathname](request, response);
}else{
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
}
http.createServer(onRequest).listen(9999);
console.log("Server has started.")
My understanding so far is that: route.routes is an empty object and route.for is a function. The function has two parameters function(path,handler) but I don't understand the part in the function i.e. this.routes[path] = handler;
From my understanding this.routes[path] is an empty object so is the code setting handler to an empty object?
and beyond this I have absolutely no clue what function onRequest(request,response){}; is doing.
Plase explain the whole code for me as I find it very disturbing not being able to understanding the basics before progressing through the E-book.
Http module that you include in first line has createserver function that takes a function as a parameter. In of the last lines we pass "onRequest" function to it. The function passed is internally invoked by http module whenever request is recived on port 9999 as also defined. Function onRequest is invoked with two parameters one is "request" that contains data like headers and body of a request that was recived. 2nd parameter is respons object it is whats sent back. It has functions that facilate this like writeHead which writes headers, .end which signals http module to sned the response finally back.
onRequest function can do whatever it wants with the request and send whatever response it wants to send back.
Here it using url module that is native to nodejs parses url and extract pathname which is everything after first / so www.mydomain.com/thispart/andthis...etc are extracted.
Then thus is done to do object lookup inside the routes. If object with key that is equal to string of this pathname exists it will return the value that is the function and if not the expression will evaluate to false and 404 part will be run. Upon match function gets invoked with response and request objects that onRequest got in the parameters.
In Javascript property of an object can be set even if its not present..
var a = {n:1};
a.x = "exists";
console.log (a.x); //exists

node.js http.request event flow - where did my END event go?

I am working on a cunning plan that involves using node.js as a proxy server in front of another service.
In short:
Dispatch incoming request to a static file (if it exists)
Otherwise, dispatch the request to another service
I have the basics working, but now attempting to get the whole thing working with Sencha Connect so I can access all the kick-ass middleware provided.
All of the action happens in dispatchProxy below
connect(
connect.logger(),
connect.static(__dirname + '/public'),
(request, response) ->
dispatchProxy(request, response)
).listen(8000)
dispatchProxy = (request, response) ->
options = {host: host, port: port, method: request.method, headers: request.headers, path: request.url}
proxyRequest = http.request(options, (proxyResponse) ->
proxyResponse.on('data', (chunk) ->
response.write(chunk, 'binary')
)
proxyResponse.on('end', (chunk) ->
response.end()
)
response.writeHead proxyResponse.statusCode, proxyResponse.headers
)
request.on('data', (chunk) ->
proxyRequest.write(chunk, 'binary')
)
# this is never triggered for GETs
request.on('end', ->
proxyRequest.end()
)
# so I have to have this here
proxyRequest.end()
You will notice proxyRequest.end() on the final line above.
What I have found is that when handling GET requests, the END event of the request is never triggered and therefore a call to proxyRequest.end() is required. POST requests trigger both DATA and END events as expected.
So several questions:
Is this call to proxyRequest.end() safe? That is, will the proxyResponse still be completed even if this is called outside of the event loops?
Is it normal for GET to not trigger END events, or is the END being captured somewhere in the connect stack?
The problem is less the end event and more the data event. If a client makes a GET requests, there's headers and no data. This is different from POST, where the requester is sending data, so the on("data") handler gets hit. So (forgive me for the JS example, I'm not that familiar with coffeescript):
var http = require('http');
// You won't see the output of request.on("data")
http.createServer(function (request, response) {
request.on("end", function(){
console.log("here");
});
request.on("data", function(data) {
console.log("I am here");
console.log(data.toString("utf8"));
});
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
If I make a curl call to this server, the data event never gets hit, because the GET request is nothing more than headers. Because of this, your logic becomes:
// okay setup the request...
// However, the callback doesn't get hit until you
// start writing some data or ending the proxyRequest!
proxyRequest = http.request(options, (proxyResponse) ->
// So this doesn't get hit yet...
proxyResponse.on('data', (chunk) ->
response.write(chunk, 'binary')
)
// and this doesn't get hit yet
proxyResponse.on('end', (chunk) ->
// which is why your response.on("end") event isn't getting hit yet
response.end()
)
response.writeHead proxyResponse.statusCode, proxyResponse.headers
)
// This doesn't get hit!
request.on('data', (chunk) ->
proxyRequest.write(chunk, 'binary')
)
// So this isn't going to happen until your proxyRequest
// callback handler gets hit, which hasn't happened because
// unlike POST there's no data in your GET request
request.on('end', ->
proxyRequest.end()
)
// now the proxy request call is finally made, which
// triggers the callback function in your http request setup
proxyRequest.end()
So yes you're going to have to manually call proxyRequest.end() for GET requests due to the logic branching I just mentioned.
my experience is that request.on('end',) is not consistently called unless it's a POST. I suspect the event (of someone making a http.request) is over before the script gets a chance to detect it.

Categories

Resources