0

尝试对 POST API 执行测试时发生以下错误

events.js:71 抛出参数 [1]; // 未处理的“错误事件”错误:在 Object.afterConnect [as oncomplete] (net.js:760:19) 的 errnoException (net.js:769:11) 处连接 ECONNREFUSED

代码如下:

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()
4

1 回答 1

1

你需要创建一个服务器(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);
});

并使用“node tweet.js”运行它

于 2013-04-21T08:46:35.037 回答