简体   繁体   中英

Node.Js error - listener must be a function

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM