Tristan C Tristan C - 1 month ago 9
HTTP Question

How to handle response from HTTP Post

I am using Angular 2 with Node.js, and I am trying to integrate braintree, which has been no simple task.

The only solution I have found to return the result object from the transaction without redirecting the page is to have the HTTP Post request send back the object. Is this possible?

onClick(){
var headers = new Headers();
headers.append('Content-Type', 'application/json');

var data = JSON.stringify({
"nonce": localStorage.getItem('nonce'),
"amount": "5.88",
"firstName": this.model.firstName,
"lastName": this.model.lastName,
"customerId": this.model.userID,
"phoneNumber": this.model.phoneNumber,
"shippingStreet": this.model.shippingStreet,
"shippingCity": this.model.shippingCity,
"shippingZip": this.model.shippingZip,
"shippingState": this.model.shippingState,
"billingStreet": this.model.billingStreet,
"billingZip": this.model.billingZip,
"billingState": this.model.billingState,
"billingCity": this.model.billingCity,
"email": this.userEmail,
"date": this.date
});

this.http.post('http://MyUrl.com:3300/checkouts', data, {headers: headers})
.subscribe();
console.log(data);
console.log("Successfully submitted data to API server...");}


Do I need to add something to the .subscribe()? And what do I need to add to the server function?

In summary, I need the HTTP Post method to post data and wait for an object from come back from the server which accepted the HTTP Post method, and created an object with the initial data.

Also, in case it matters, my server and front end are on different ports.

Answer

If I understand your question correctly, you need to give a callback function to the .subscribe method in order to do what you'd like to do. the callback should take a success and error function, for example):

this.http.post('http://MyUrl.com:3300/checkouts', data, {headers: headers})
    .subscribe(
        (response) => {console.log(response)},
        (error) => {console.log(error)}
    );