Search code examples
httpmeteorconnectioniron-router

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


I have created a server side route (using iron-router). Code is as follows :

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.
});

This app is running on port 3000 on my local. Now I have created another dummy app running on port 5000. Frrom the dummy app, I am firing a http.post request and then listening it on the app on 3000 port. I fire the http.post request via dummy app using the below code :

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;
}

But I get the following error on the callback :

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

Not able to figure out whats the problem here. The server side route is successfully called, but the .post() method is not being entered. Using meteor version 1.6 192.168.1.5 is my ip addr


Solution

  • Okay so if I use Router.map function, the issue is resolved.

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