Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.Js error - listener must be a function

Tags:

node.js

I am trying to build an endpoint /order.... where an order a POST request can be made.

var http = require('http');

var options = {
  hostname: '127.0.0.1'
  ,port: '8080'
  ,path: '/order'
  ,method: 'GET'
  ,headers: { 'Content-Type': 'application/json' }
};

var s  = http.createServer(options, function(req,res) {

  res.on('data', function(){
       // Success message for receiving request. //
       console.log("We have received your request successfully.");
  });
}).listen(8080, '127.0.0.1'); // I understand that options object has already defined this. 

req.on('error', function(e){
  console.log("There is a problem with the request:\n" + e.message);
});

req.end();

I get an error "listener must be a function"....when trying to run it from command line - "node sample.js"

I want to be able to run this service and curl into it. Can someone proof read my code and give me some basic directions on where I am going wrong? and how I may improve my code.

like image 351
Philo Avatar asked Sep 18 '26 00:09

Philo


1 Answers

http.createServer() does not take an options object as a parameter. Its only parameter is a listener, which must be a function, not an object.

Here's a really simple example of how it works:

var http = require('http');

// Create an HTTP server
var srv = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('okay');
});

srv.listen(8080, '127.0.0.1');
like image 168
Trott Avatar answered Sep 22 '26 01:09

Trott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!