AnonymousCoder
AnonymousCoder

Reputation: 592

Calling an existing API using Express passing json body

I am new to NodeJs / Express. I am trying to create an API which will in turn call an existing API which basically creates the product with some modification. basically the API "products" i am calling uses POST method. Which Basically expects data to be passed in JSON format. But here I get the error from the target API saying that body is not passed.

let json = {"id": "", "name" : ""};

      app.get('/createProduct/:product_id', function (req, res) {
        let url = 'https://somewebsite/api/products'
        json.id = req.params.product_id;

        req.headers['token'] = getToken();
        req.headers['timestamp'] = getTimeStamp();
        req.body = json;

        req.pipe(request(url)).pipe(res);
      }); 

Am I missing something?

Upvotes: 1

Views: 212

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30715

You don't necessarily need to pipe the req object to the request call in this case, you could just make a request.post call, you can still pipe the output from this, I think it will give you the result you wish:

let json = {"id": "", "name" : ""};

app.get('/createProduct/:product_id', function (req, res) {
    let url = 'https://somewebsite/api/products';
    // Create headers for outgoing call.
    let headers = { 
        token: getToken(),
        timestamp: getTimeStamp()
    }
    // Populate the json.id value.
    json.id = req.params.product_id;
    request.post({ url, headers, body: json, json: true }).pipe(res);
});

Also for testing purposes, I suggest you create a POST listener to see what you're passing to the service, you can easily do this in express:

app.post("/post_test", bodyParser.json(), (req, res) => {
    console.info("/post_test: headers:", req.headers);
    console.info("/post_test: body:", req.body);
    res.status(201).send("All good");
})

To use this simply change the url in the app.get call to:

http://localhost:<port>/post_test

And remember to change back !

Upvotes: 1

Related Questions