2016-09-14 159 views
0

我正在构建一个应用程序,并且在从客户端发出请求时发送问题,将其发送到我的服务器,让服务器进行API调用,然后发送结果回到客户端。我正在使用Node和Request-Promise模块。异步Javascript请求问题(节点,请求承诺模块)

这里是客户端代码:

$(document).ready(function() { 
    var artistSearch =() => { 
     const q = $('.artistName').val(); 
     $.ajax({ 
      type: "POST", 
      url: "http://localhost:3000/request", 
      data: {artist: q}, 
     }) 
     .done(function(data) { 
      console.log('data: ', data) 
     }) 
    }; 

    $(".artistSearch").submit(() => { 
     artistSearch(); 
    }); 
}); 

这成功地向服务器的请求:

app.post('/request', (req, res) => { 
    const artist = req.body.artist; 
    const searchURL = "https://api.spotify.com/v1/search?  q="+artist+"&type=artist"; 
    var targetObj; 

    var options = { 
     uri: searchURL 
    }; 

    rp(options) 
     .then(function (data) { 
      console.log(data); 
      res.send(data); 
     }) 
     .then(function() { 
      console.log('complete'); 
     }) 
     .catch(function (err) { 
      console.log('error') 
     }); 

});

它最终成功地从API调用抓取数据,但从未将它发送回客户端!如果我在我的承诺之外做res.send(),我可以在客户端收到数据。

有什么我失踪?提前致谢!

+0

您不会得到_any_日志? –

+2

这是一个错字错误哈哈。您在代码中发送字符串“data”而不是变量“data”。 –

+0

这是出于测试目的 - 即使仍然没有数据通过。 –

回答

0

试试这个

var options = { 
    uri: searchURL, 
    simple: false, 
}; 

rp(options) 
    .then(function (data) { 
     console.log(data); 
     res.status(200).send(data).end(); 
    }) 
    .then(function() { 
     console.log('complete'); 
    }) 
    .catch(function (err) { 
     console.log('error') 
    }); 
0

我认为客户端没有接收数据,但其认为有更多的数据连接不正确终止。这是因为你没有指定头文件,而模块http找不到内容长度。

rp(options) 
    .then(function (data) { 
     console.log(data); 
     // res.send(data); 

     // assume data is JSON. 
     res.setHeader (200, {'Content-Type': 'application/json', 
          'Content-Length':data.byteLength}); 
     res.end(data); //Send data immediately. 
    }) 

...

如果数据是一个字符串,你需要使用data.length代替。实际上,如果数据是字符串,那么在默认情况下,标题是{'Content-Type': 'application/json', 'Content-Length':data.length}