Nodejs sending external API POST request

BroBan

i am trying to send a POST request from my angularjs controller to the nodejs server which should then send a full POST request to the external API and this way avoid CORS request as well as make it more secure as i'm sending relatively private data in this POST request.

My angularjs controller function for making the post request to the nodejs server looks like this and it works fine:

var noteData = {
    "id":accountNumber,
    "notes":[
        {
            "lId":707414,
            "oId":1369944,
            "nId":4154191,
            "price":23.84
        }
    ]
}

var req = {
    method: 'POST',
    url: '/note',
    data: noteData
}

$http(req).then(function(data){
    console.log(data);
});

Now the problem lies in my nodejs server where i just can't seem to figure out how to properly send a POST request with custom headers and pass a JSON data variable..

i've trierd using the nodejs https function since the url i need to access is an https one and not http ,i've also tried the request function with no luck.

I know that the url and data i'm sending is correct since when i plug them into Postman it returns what i expect it to return. Here are my different attempts on nodejs server:

The data from angularjs request is parsed and retrieved correctly using body-parser

Attempt Using Request:

app.post('/buyNote', function (req, res) {
var options = {
    url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': apiKey
    },
    data = JSON.stringify(req.body);
};


 request(options, function (error, response, body) {
     if (!error) {
         // Print out the response body
         // console.log(body)
         console.log(response.statusCode);
         res.sendStatus(200);
     } else {
         console.log(error);
     }
 })

This returns status code 500 for some reason, it's sending the data wrongly and hence why the server error...

Using https

var options = {
    url: 'https://api.lendingclub.com/api/investor/v1/accounts/' +    accountNumber + '/trades/buy/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': apiKey
    }
   };
   var data = JSON.stringify(req.body);


var req = https.request(options, (res) => {
 console.log(`STATUS: ${res.statusCode}`);
 console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
 res.setEncoding('utf8');
 res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
 });
 res.on('end', () => {
console.log('No more data in response.');
 });
  });

req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
 });


req.write(data);
req.end();

Https attempt return a 301 status for some reasons...

Using the same data, headers and the url in Postman returns a successful response 200 with the data i need...

I don't understand how i can make a simple http request...

Please note: this is my first project working with nodejs and angular, i would know how to implement something like this in php or java easily, but this is boggling me..

BroBan

So after a lot of messing around and trying different things i have finally found the solution that performs well and does exactly what i need without over complicating things:

Using the module called request-promise is what did the trick. Here's the code that i used for it:

const request = require('request-promise');

const options = {
    method: 'POST',
    uri: 'https://requestedAPIsource.com/api',
    body: req.body,
    json: true,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'bwejjr33333333333'
    }
}

request(options).then(function (response){
    res.status(200).json(response);
})
.catch(function (err) {
    console.log(err);
})

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related