You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让客户端获取服务器返回的里程数据并打印至控制台?

问题:无法从Fetch Response中提取里程数值

客户端通过表单提交两组经纬度坐标到服务器的/handle-coordinates端点,服务器成功调用Google Maps API获取里程数据并返回,但当前客户端代码仅能打印出Fetch返回的Response对象,无法获取并打印实际的里程数值。

原服务器端代码

//Server side code

app.post("/handle-coordinates", async function (req, res) {
    var config = {
      method: 'get',
      url: `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${req.body.coordinates.lat}, ${req.body.coordinates.long}&destinations=${req.body.coordinates.lat2},${req.body.coordinates.long2}&units=imperial&key=KEY`,
      headers: {}
    };

    axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data.rows[0].elements[0].distance.text));
        res.send(response.data.rows[0].elements[0].distance.text);
      })
      .catch(function (error) {
        console.log(error);
      });

  })


app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));

原客户端代码

//Client side code
var form = document.getElementById("form")
var origin = document.getElementById("origin")
var destination = document.getElementById("destination")



form.addEventListener('submit', function(event) {
    var formSubmitted = true
    event.preventDefault();
    console.log("submitted");
    var formData = {
        lat: document.getElementById("lat").value,
        long: document.getElementById("long").value,
        lat2: document.getElementById("lat2").value,
        long2: document.getElementById("long2").value,
    };
    console.log(formData);
    fetch('/handle-coordinates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ coordinates: formData })
    }).then(function(result) {
        console.log(result)
      })
    origin.value = ""
    destination.value = ""
});

问题原因

Fetch API返回的Response对象只是包含响应状态、头等元数据的容器,并没有直接包含响应体内容。要获取服务器返回的里程文本,需要调用Response.text()方法(因为服务器返回的是纯文本格式)来读取响应体。

修改后的客户端代码

只需要修改fetch的回调链,先调用text()获取响应内容,再打印:

fetch('/handle-coordinates', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ coordinates: formData })
})
.then(function(result) {
    // 调用text()读取纯文本响应体
    return result.text();
})
.then(function(distanceText) {
    // 这里就能拿到实际的里程数值并打印
    console.log("里程数值:", distanceText);
})
.catch(function(error) {
    // 新增错误处理,捕获请求或解析过程中的异常
    console.error("请求出错:", error);
})

补充说明

如果后续服务器改为返回JSON格式数据(比如用res.json()代替res.send()),则需要调用Response.json()来解析响应体。当前服务器返回的是纯文本,所以用text()即可。

内容的提问来源于stack exchange,提问作者Kavi Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:30:49