【问题标题】:How to return value from node to origin (angular2 request)如何将值从节点返回到原点(angular2 请求)
【发布时间】:2016-11-06 12:44:44
【问题描述】:

我的 nodejs 实例中有代码,它接收到一个发布请求(成功)并且还显示了通过 json 发送的参数(我在服务器端需要 body-parser)。收到帖子请求后,我立即执行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("something returned");

编辑:

这是我的代码现在的样子,但仍然失败(没有触发 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 是一个简单的日志“收到反馈”...

【问题讨论】:

    标签: node.js angular


    【解决方案1】:

    你会的

    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 在此范围内不存在。它将是undefined 内parseResponse

    【讨论】:

    • 已更新。请同时添加parseResponse 的代码并在this.parseResponse 之前尝试console.log
    【解决方案2】:

    试试这个,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); }
        );
    

    【讨论】:

      【解决方案3】:

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

      return to_return;
      

      您没有确切地提到您的服务器代码在哪里运行。 This doc 明确表示核心 HTTP 模块已经创建了响应对象,并且它总是将它与请求对象一起传递。所以理想情况下你只需要使用响应对象。并像 send 一样调用它的 API。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多