0
votes

Following error occurred while trying to execute a test for the POST API

events.js:71 throw argumentt[1]; // unhandled 'error event' Error: connect ECONNREFUSED at errnoException (net.js:769:11) at Object.afterConnect [as oncomplete] (net.js:760:19)

The code is as follows:

var http = require('http');
assert = require('assert')

var opts = {
host:'localhost',
port:8000,
path:'/send',
method:'POST',
headers:{'content-type':'application/x-www-form-urlencoded'}
}

var req = http.request(opts,function(res) {
res.setEncoding('utf8')

var data = ""
res.on('data', function(d) {
data += d
})

res.on('end',function() {
assert.strictEqual(data, '{"status":"ok","message":"Tweet recieved"}')
})
})

req.write('tweet=test')
req.end()
1
The 'connection refused' error probably indicates that nothing is listening on localhost on port 8000. You could check on Linux with: 'sudo lsof -Pn | grep LISTEN' and see if anything is listening on 8000, or try using 'telnet localhost 8000' and see if you also get connection refused. - Kyle Burton
I am using windows 7,Tell me if u have got any solution regarding that. Thanks. - AbhishekDwivedi
You can use telnet on windows, though you may have to enable it (I did): fettesps.com/windows-7-enable-telnet Since I have no process listening on port 8000, I get 'Connect failed' on Windows. - Kyle Burton
I enabled it still error persist. - AbhishekDwivedi

1 Answers

1
votes

you need to create a server (tweet.js)

var express = require('express');
var app = express.createServer();
app.listen(8000);
var tweets = [];
app.get('/', function(req, res) {
  res.send('Welcome to Node Twitter');
})
app.post('/send', express.bodyParser(), function(req, res) {
  if (req.body && req.body.tweet) {
    tweets.push(req.body.tweet);
    res.send({status:"ok", message:"Tweet received"});
  } else {
    //no tweet?
    res.send({status:"nok", message:"No tweet received"});
  }
});
app.get('/tweets', function(req,res) {
  res.send(tweets);
});

and the run it with "node tweet.js"