将javascript http响应保存到变量时遇到问题

Having trouble saving javascript http response to a variable

本文关键字:变量 遇到 问题 保存 javascript http 响应      更新时间:2023-09-26

我一直在bash中摆弄这个维基百科节点模块,在保存对变量的响应时遇到了一些问题。我可以使用console.log(response)来查看完整的响应,但我不能让它停留在变量上。

我试着查看响应的类型,但它只是返回未定义的结果。有什么想法吗?

var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
    console.log(typeof response);
});

理想情况下,我想将具有html对象的响应分配给一个变量,然后使用cheerio通过jQuery选择器获取html对象的片段,但我认为我至少需要先将其获取到一个变量中,对吧?

这是回应的一部分。

 { title: 'Clifford Brown',
  redirects: [],
  text: { '*': '<div class="hatnote">For the scrutineer for the Eurovision Song Contest, see <a href="/wiki/Clifford_Brown_(scrutineer)" title="Clifford Brown (scrutineer)">Clifford Brown (scrutineer)</a>.

编辑/修复

根据@idseew的评论,我得以将其付诸实践。所有的事情都需要在回调中完成,所以我没有在请求后调用变量,而是像这样在回调中返回它,这让我可以访问函数之外的变量。

var wikipedia = require("node-wikipedia");
var data;
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
data = response;

})

StackOverflow上出现了很多这样的问题,它们都源于不理解AJAX的异步本质。您的代码不会在.data()调用处阻塞以等待服务器响应。在该调用之后运行的任何代码行都将立即运行,而回调函数中的代码将在将来的某个时刻,即从服务器返回数据之后运行。响应于获取数据所做的任何操作都必须发生在该回调中。

var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
    console.log(typeof response);
    // do something with the response here
});
// any code here will run before the above callback is invoked.
// don't try to do anything with the response here.