How to http.post with json parameter?

#1

Hi, how can i get a succesful response via HTTP from my API?
Issueing the request via curl works well. Tried it via meteor (serverside) but this didn’t work out unfortunately (ECONNRESET):

HTTP.call( 'POST', 'http://127.0.0.1:1234', {
  data: {
    'username':'satoshi',
    'method':'genes',
    'ipaddr':'somePrivateUrl',
    'port': 3298
  }
}, function( error, response ) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( response );
  }
});

the corresponding curl which works is:

curl --url "http://127.0.0.1:1234" --data "{\"username\":\"satoshi\",\"method\":\"genes\",\"ipaddr\":\"somePrivateUrl\",\"port\":3298}"

any help is much appreciated!

(running the same in nodeJS with ‘http’ worked as well - i still prefer using native meteor funcs)

#2

The --data option to curl specifies that form-encoded data is to be sent (sets the header content-type application/x-www-form-urlencoded).

The recommended way to send form-encoded data in a POST request with Meteor is by using the params field (not data), which also sets that header. So, you should try:

HTTP.call( 'POST', 'http://127.0.0.1:1234', {
  param: {
    'username':'satoshi',
    'method':'genes',
    'ipaddr':'somePrivateUrl',
    'port': 3298
  }
}, function( error, response ) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( response );
  }
});

Incidentally, you can use the non-callback form on the server, which is shorter:

const response = HTTP.call( 'POST', 'http://127.0.0.1:1234', {
  params: {
    'username':'satoshi',
    'method':'genes',
    'ipaddr':'somePrivateUrl',
    'port': 3298
  }});

and use try/catch for error handling.

1 Like