我正在构建一个应用程序,并且在从客户端发出请求时发送问题,将其发送到我的服务器,让服务器进行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(),我可以在客户端收到数据。
有什么我失踪?提前致谢!
您不会得到_any_日志? –
这是一个错字错误哈哈。您在代码中发送字符串“data”而不是变量“data”。 –
这是出于测试目的 - 即使仍然没有数据通过。 –