-4

I'm trying to make a local server using nodeJs but its not working.

What is tried

var http = require('http');

http.createServer(function(req, res) {
    res.write('Hello');
    req.end();
}).listen(8080);
Rohit Verma
  • 3,657
  • 7
  • 37
  • 75

2 Answers2

0

The res (which stand for response) in the callback is a Stream. After you write all you want (headers, body) to the stream, you must end it like so:

res.end();

What you have is req.end(). Using req instead of res was your error.

Also, since you only write one line in this contrived example, you could write the buffer and end the stream in one go:

const server = http.createServer(function (req, res) {
    res.end('Hello');
});

server.listen(8080);

Docs for response.end

Marian
  • 3,789
  • 2
  • 26
  • 36
0

Be careful when using response.end!

What is the difference between response.end() and response.send()?

response.end() will always send an HTML string, while response.send() can send any object type. For your example, both will serve the purpose since you are sending an HTML string of 'hello', but keep these cautions in mind as you proceed to build your server!

var http = require('http');

//Example with response.end()
http.createServer(function(request, response) {
    response.end('Hello');
}).listen(8080);

//Example with response.send()
http.createServer(function(request, response) {
    response.send('Hello');
}).listen(8080);

//Example with res.send() object
http.createServer(function(request, response) {
    response.send({ message: 'Hello', from: 'Happy Dev' });
}).listen(8080);
Calvin Ellis
  • 325
  • 2
  • 8
  • I find it ironic that you made same "typo" as the OP :) you meant `res.send`, not `req.send`. Also note that this answer is about express library response, while OP is using `http` module. Instances of `http.ServerResponse` don't have `send` method, according to docs. – Marian Oct 13 '18 at 14:51
  • This is EXACTLY why I type out the full name for response and request as the params.... having only two variables named that similarly does not make for easy to read code and as we just saw, leads to mistakes. Let me update the answer. – Calvin Ellis Oct 13 '18 at 14:59