Some User
Some User

Reputation: 5817

Node.js + Sending API Request to Third Party Service

I have a Node console app. In my app, I am trying to send some data to a third-party web service. I can successfully add data via the third-party web service via POSTMAN. In my Postman, I have a request setup like this:

Headers

api-key
{my key}

Content-Type
application/json

Body

{
  "value": [
    { 
      "@operation": "send",
      "id":"1",
      "name":"Hello",
      "position": { "type": "Point", "coordinates": [90.000000, 0.000000] },
      "tags":["january", "friends"]
    }
  ]
}

I am now trying to replicate sending this data via Node. In an attempt to do this, I've written the following:

var ops = {
  host: 'example.com',
  path: '/api/upload?version=2',
  method: 'POST',
  headers: {
    'api-key':'[my key]',
    'Content-Type': 'application/json'
  }
};

var r = https.request(ops, (res) => {
  res.on('data', (d) => { 
    console.log(res.statusCode); 
    console.log(res.statusMessage);
  });
});

var data = {
  "value": [
    req.body.record    // req is passed in via express 
  ]
};
console.log(data);

r.write(JSON.stringify(data));
r.end();

When the line console.log(data); is executed, I see the following in the console window:

{ value:
   [ { '@operation': 'send',
       id: '1',
       name: 'Hello',
       position: [Object],
       tags:[Object]
    } ] }

I'm not sure if this is a printing problem or an actual problem. Either way, my real issue is that when I send my request, I see the following also printed in the console window:

400
Bad Request

That data looks correct. I don't understand why I'm getting a 400 when I try to send from Node. Yet, it works just fine from Postman. Does it have to do with the quotation marks? I thought JSON.stringify handled that.

What am I doing wrong?

Upvotes: 0

Views: 1789

Answers (2)

Emil Alkalay
Emil Alkalay

Reputation: 496

I would try

console.log(JSON.stringify(data));

Instead of

console.log(data);

and then decide what is wrong. This will give me full data in way it is sent to server.

Update: I have made quick experiment and received following output:

{"value":[{"@operation":"send","id":"1","name":"Hello","position":{"type":"Point","coordinates":[90,0]},"tags":["january","friends"]}]}

The difference with the original JSON is in way how the coordinates are sent to the web service (as integers), which can be your problem.

Upvotes: 0

floatingLomas
floatingLomas

Reputation: 8727

Honestly, unless you have a really good reason not to, just use something like request. It's way easier/cleaner than trying to build it yourself.

I can't answer any more specifically without knowing what the API you're talking to is expecting.

Also, in your res.on('data'), just console.log(req); and see what else is hiding in there; it might help you solve this with your existing code.

Upvotes: 2

Related Questions