提问者:小点点

如何将值从节点返回到原点(angular2请求)


我在nodejs实例中有代码,它接收post请求(成功),并且还显示通过json发送的参数(我需要在服务器端使用body-parser)。一旦收到post请求,我立即执行return“testing”;以检查值是否成功返回。但是,我的angular2回调(如图所示)不会激发或显示任何日志。知道为什么吗?

  var to_send = JSON.stringify({"test": argument});

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

   this.http
    .post('http://localhost:8080/', 
      to_send, {
        headers: headers
      })
    .map((res) => res.json() )
    .subscribe(
      (response) => { console.log("Success Response" + response)},
      (error) => { console.log("Error happened" + error)},
      () => { this.parseResponse(res); }
    );

函数parseResponse只是console.logs(“返回的东西”);

下面是我的代码现在的情况,仍然失败(没有触发parseResponse内部的日志):

var to_send = JSON.stringify({"test": argument});

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

  this.http
    .post('http://localhost:8080/', 
      to_send, {
        headers: headers
      })
    .map((res) => res.json() )
    .subscribe(
      (response) => { console.log("Success Response",response)},
      (error) => { console.log("Error happened",error)},
      () => { this.parseResponse(res); }
    );

在我的服务器中,我将返回以下内容:

var to_return = {};

to_return["message"] = "success";

return to_return;

然而,它根本不起作用。知道为什么吗?parseresponse是一个简单的日志“收到的反馈”。。。


共3个答案

匿名用户

你知道吗

this.http...
  .map((res) => res.json() )

通过此操作,您可以将响应转换为JSON,因为它不是JSON,所以它将失败。您可以使用text()方法来获取字符串:

.map((res) => res.text())

也可以从后端返回一个对象:

return {result: "testing"}

和读取subscribe内的字段result

更新:

您可以在map方法中输出res,查看它真正包含的内容:

.map((res) => {
  console.log(res);
  return res.json();
})

还有一件事:调用this.parseresponse(res)res在此作用域中不存在。它将是parseresponse内部的undefined

匿名用户

尝试以下操作,self.parseresponse(res);:

...
 let self = this;
 this.http
    .post('http://localhost:8080/', 
      to_send, {
        headers: headers
      })
    .map((res) => res.json() )
    .subscribe(
      (response) => { console.log("Success Response",response)},
      (error) => { console.log("Error happened",error)},
      () => { self.parseResponse(res); }
    );

匿名用户

我怀疑你的服务器代码。您是否验证了服务器是否真的发送了任何响应。而且它真的到达了你的客户端?

return to_return;

您还没有确切地提到您的服务器代码正在运行的位置。这个文档清楚地说明了核心HTTP模块已经创建的响应对象,并且它总是将它与请求对象一起传递。所以理想情况下,您只需使用响应对象。并像send一样调用它的API。

但您根本没有显示任何使用response对象的代码。