【问题标题】:Node JS Request external API and send it back to client side AJAXNode JS请求外部API并将其发送回客户端AJAX
【发布时间】:2019-04-18 00:51:47
【问题描述】:

所以我有一个 Node.js 服务器,它的路由只做一件事。当通过客户端单击按钮调用时,它会转到此处并从外部 API 获取数据。

app.get('/ajaxcall', function(req, res) {
const options = {
    url: 'hidden url',
    method: 'POST',
};

request(options, function(err, request, body) {
    if (err) {
        request.send('There was an error with fetching API');
    }
    else {
        console.log(res.statusCode);
        return res.end(JSON.stringify(body));
    }
});
});

然后我有这个位从服务器获取这些数据。

$(document).ready(function(){
$('#searchButton').click(function(event){
event.preventDefault()
$.ajax({
  type: 'GET',
  url: '/ajaxcall',
})
.done(function(result){
  let data = jQuery.parseJSON(result);
  console.log(data)
  console.log(data[0].formatted_address)
})
.fail(function(xhr, status, error){
  console.log(error)
})
.always(function(data){})
})
})

问题是console.log(data) 会将所有内容输出到控制台,但console.log(data.[0].formatted_address)outputs 未定义。

我正在尝试从我返回的这个 JSON 中获取数据,以便将其显示在网站上。谁能告诉我为什么 console.log(formatted_address) 在客户端不起作用,但在服务器端起作用?有没有办法遍历这个 JSON 对象并选择我需要的位?

以下是 JSON 的外观 JSON screenshot

【问题讨论】:

    标签: javascript node.js json ajax api


    【解决方案1】:

    下面是一个示例,说明如何使用 forEach 数组函数更改 .done 函数以循环访问部分数据。

    .done(function(result){
      let data = jQuery.parseJSON(result);
    
      data.results.forEach(function(result) {
            console.log(result.formatted_address);
            console.log(result.geometry.location.lat, result.geometry.location.lng);
            console.log(result.icon);
        });
    })
    

    【讨论】:

      【解决方案2】:

      如果您发布的 JSON 被反序列化到前端的 data 变量中,则似乎 data 是一个 JSON 对象,其中包含一个 results 字段,该字段是一个数组,而不是 @987654324 @object 本身就是一个数组。

      尝试类似data.results[0].formatted_address

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        • 2014-09-13
        • 1970-01-01
        • 2019-05-31
        • 1970-01-01
        相关资源
        最近更新 更多