Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js http.createServer how to get error

I am new to node.js and am trying to experiment with basic stuff.

My code is this

var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

Here's the question - how can I see the exceptions thrown (or events thrown) when calling createServer ? I tried try/catch but it doesn't seem to work . In module's API I couldn't find any reference to it . I am asking because I accidentally started a server on a taken port(8888) and the error I got (in command-line) was Error : EDDRINUSE , this is useful enough but it would be nice to be able to understand how errors are caught in node .

like image 378
user1551120 Avatar asked Sep 19 '12 14:09

user1551120


People also ask

What does HTTP createServer return?

Return Value: HTTP Server object. Node.js Version: 0.1.13.

How do you get a response body in node JS?

request docs contains example how to receive body of the response through handling data event: var options = { host: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; var req = http. request(options, function(res) { console. log('STATUS: ' + res.

How do I use HTTP request in node JS?

Step to run the application: Open the terminal and write the following command. Approach 3 : Here we will send a request to updating a resource using node-fetch library. If you are already worked with Fetch in browser then it may be your good choice for your NodeJS server. Rewrite the index.


1 Answers

You can do this by handling the error event on the server you are creating. First, get the result of .createServer().

var server = http.createServer(function(request, response) {

Then, you can easily handle errors:

server.on('error', function (e) {
  // Handle your error here
  console.log(e);
});
like image 125
Brad Avatar answered Sep 29 '22 02:09

Brad