【问题标题】:Unable to return JSON response to client using Node无法使用 Node 向客户端返回 JSON 响应
【发布时间】:2016-10-10 18:06:01
【问题描述】:

我无法根据请求将 JSON 对象返回给客户端 - 我正在处理对“/btc”的第一次 GET 调用。

//Main server to recieve requests
http.createServer(function(req,res){

 switch(req.method){
      case 'GET':
           switch(req.url){
                case '/btc':
                     callBtcApi(req,res)
                     console.log(' btc called');
                     break;
                case '/wallet':
                     callBtcWallet(req,res)
                     console.log('wallet called');
                     break;
                case '/weather':
                     callWeather(req,res);
                     console.log('weather called');
                     break
                default:
                     console.log('calling but not hitting');
                     break;
           }
      case 'POST':
           switch(req.url){
                case '/update':
                     console.log('update called');
                     break;
           }
 }

}).listen(3000);

callBtcApi() 下面,查询一个比特币 API 并成功返回一个 JSON 对象(我确实打算用这个函数做更多的事情,只是先了解基础知识)。 callBtcApi() 被成功调用。

function callBtcApi(req,res){

message = '';

 https.get('https://api.bitcoinaverage.com/ticker/global/GBP/', function(res){
      res.on('data',function(data){
           message += data;
      });
      res.on('end',function(){
           console.log('props called ;)');
           writeToCLient(res,message);
      });
 }).on('error', function(e){
      console.error(e);
 });
}

我遇到的问题是当我将这些数据传递给 res.on('end') 中的 writeToCLient() 函数时。我在终端收到的错误是

TypeError: res.setHeader is not a function

我知道消息被传递到函数 writeToCLient() 中,因为如果我暂时隐藏所有 res.() 调用,我可以在 console.log(message) 时看到终端中的数据。

function writeToCLient(res,message){
 console.log(message);
 res.statusCode = 200;
 res.setHeader('Content-Type','application/json');
 res.end(JSON.stringify(message));
}

我已经搜索了谷歌,但没有找到任何可以解释可能是什么问题的东西。问题是否可能归结为从位于我的主服务器内的 callBtcApi() 内部调用 HTTP.get() 请求? 谢谢

【问题讨论】:

  • 您传递了错误的响应对象。

标签: json node.js http httprequest


【解决方案1】:

你可以试试这个吗?

function callBtcApi(request,response){

message = '';
 https.get('https://api.bitcoinaverage.com/ticker/global/GBP/', function(res){
      res.on('data',function(data){
           message += data;
      });
      res.on('end',function(){
           console.log('props called ;)');
           writeToCLient(response,message);
      });
 }).on('error', function(e){
      console.error(e);
 });
}

【讨论】:

  • 那太好了,感谢 LuisPinto。正如 SLaks 关于响应对象所说,这是问题的原因吗? callBtcApi() 函数是否构建在主服务器响应对象之上?希望这是有道理的,我只是想了解我哪里出错了。
  • 是的,你是从https.get而不是callBtcApi传递 res 对象,因为变量 res 被覆盖了。所以你只需要改变变量名;)
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
相关资源
最近更新 更多