如何处理来自HTTP Post的响应

时间:2016-10-16 03:26:19

标签: node.js http angular

我正在使用Angular 2和Node.js,我正在尝试集成braintree,这不是一项简单的任务。

我发现从事务中返回结果对象而不重定向页面的唯一解决方案是让HTTP Post请求发送回对象。这可能吗?

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...");}

我是否需要在.subscribe()中添加内容?我需要添加什么来添加到服务器功能?

总之,我需要HTTP Post方法发布数据并等待一个对象从接受HTTP Post方法的服务器返回,并创建一个包含初始数据的对象。

此外,如果重要,我的服务器和前端位于不同的端口。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你需要给.subscribe方法提供一个回调函数,以便你做你想做的事。回调应该采用成功和错误函数,例如):

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