Meteor HTTP.POST 在同一台机器上调用(用于测试)

Meteor HTTP.POST call on same machine (for testing)

我已经创建了一个服务器端路由(使用 iron-router)。代码如下:

Router.route( "/apiCall/:username", function(){
var id = this.params.username;
},{ where: "server" } )

.post( function(req, res) {
// If a POST request is made, create the user's profile.
//check for legit request
console.log('post detected')
var userId = Meteor.users.findOne({username : id})._id;

})
.delete( function() {
// If a DELETE request is made, delete the user's profile.
});

此应用 运行 在我本地的端口 3000 上。现在我在端口 5000 上创建了另一个虚拟应用程序 运行。我从虚拟应用程序发出一个 http.post 请求,然后在应用程序的 3000 端口上侦听它。我使用以下代码通过虚拟应用程序触发 http.post 请求:

apiTest : function(){
    console.log('apiTest called')
     HTTP.post("http://192.168.1.5:3000/apiCall/testUser", {
      data: [
                {
                    "name" : "test"
                }
            ]
    }, function (err, res) {
        if(!err)
            console.log("succesfully posted"); // 4
        else
            console.log('err',err)
    });
    return true;
}

但是我在回调中收到以下错误:

 err { [Error: socket hang up] code: 'ECONNRESET' }

无法弄清楚这里的问题是什么。 服务器端路由调用成功,但是没有进入.post()方法。 使用流星版本 1.6 192.168.1.5 是我的 ip 地址

内容类型似乎未设置 application/json。所以你应该这样做......

好的,如果我使用 Router.map 函数,问题就解决了。

Router.map(function () {
this.route("apiRoute", {path: "/apiCall/:username",
where: "server",
action: function(){
  // console.log('------------------------------');
  // console.log('apiRoute');
  // console.log((this.params));
  // console.log(this.request.body);
  var id = this.params.username;

  this.response.writeHead(200, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  });

  if (this.request.method == 'POST') {
    // console.log('POST');
    var user = Meteor.users.findOne({username : id});
    // console.log(user)
    if(!user){
      return 'no user found'
    }
    else{
      var userId = user._id;
    } 

  }
 });
 });