【问题标题】:An API call return the body, but can't reach the propertiesAPI 调用返回正文,但无法访问属性
【发布时间】:2021-02-08 11:31:14
【问题描述】:

我目前正在使用Mapbox geocoding API,但发现了一个奇怪的错误。

const geocode = async (address, callback) => {
    const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=token&limit=1`
    try {
        const req = await got(url, { responseType: 'json' })
        console.log(req.body) //I get the data
        console.log(req.body.type) //I get undefined
    } catch (error) {
        console.log(error);
        callback(undefined, 'Can\'t reach the geocoding API')
    }
}

此 API 的结果示例:

    {
        "type": "FeatureCollection",
        "query": [
        "boston"
        ],
        "features": [
        {
        "id": "place.9391334652012190",
        "type": "Feature",
        "place_type": [
        "place"
        ],
        "relevance": 1,
        "properties": {
        "wikidata": "Q100"
        },
        "text": "Boston",
        "place_name": "Boston, Massachusetts, United States",
        "bbox": [
        -71.1255750165112,
        42.3196059806256,
        -70.9860500028801,
        42.3974009328397
        ],
        "center": [
        -71.0596,
        42.3605
        ],
        "geometry": {
        "type": "Point",
        "coordinates": [
        -71.0596,
        42.3605
        ]
        },
        "context": [
        {
        "id": "region.8307399429561540",
        "wikidata": "Q771",
        "short_code": "US-MA",
        "text": "Massachusetts"
        },
        {
        "id": "country.19678805456372290",
        "wikidata": "Q30",
        "short_code": "us",
        "text": "United States"
        }
        ]
        }
        ],
        "attribution": "NOTICE: © 2021 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."
}

实际上,当我调用 req.body 时,API 会为我提供所有数据。

但是当我想访问一个特定的值,比如类型,对于这个例子,它返回 undefined,我不明白为什么?

谢谢。

【问题讨论】:

  • 什么是got?很难说不知道那是什么,但我猜你的回复仍然是一个字符串,还没有通过JSON.parse
  • 是的,有,我忘了说。

标签: javascript node.js api mapbox


【解决方案1】:

假设您正在谈论got,您的response.body 成功请求将如下所示

{
  status: 'success',
  data: <your-response-body-here>
}

因此,为了访问响应负载,您需要执行以下操作:

 const response = await got(url, { responseType: 'json' })
 console.log(response.body.data);

请注意,您可以通过传递 resolveBodyOnly 选项来简化此操作。然后response 将直接保存响应负载:

const response = await got(url, { responseType: 'json', resolveBodyOnly: true })
console.log(response.data);

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2011-03-29
    • 2016-12-21
    • 2015-08-02
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多