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

客户端向服务器发送地理位置报错:Cannot read properties of undefined (reading 'loc')

解决客户端向Express服务器传递地理位置时的TypeError问题

问题描述

实现客户端向服务器传递地理位置功能时,触发错误:TypeError: Cannot read properties of undefined (reading 'loc')。前端已成功获取并打印用户地理位置,但通过fetch发送POST请求到Express服务器后,服务器读取req.body.loc时触发该错误。尝试在代码块外声明loc变量无效,目标是传递地理位置用于后续天气应用开发。

相关代码

前端HTML文件代码

<script>
        // Automatically get the user's location
        if ("geolocation" in navigator) {

            navigator.geolocation.getCurrentPosition( (position)=>{

                const latitude = position.coords.latitude;
                const longitude = position.coords.longitude;
                
                // creating JSON object to send to server
                const loc = {latitude:latitude, longitude:longitude};

                console.log('\n Location :-',loc,'\n'); //this line successfully shows loc
                
                // I got error as Cannot read properties of undefined (reading 'loc')
                fetch('/',{

                    method : "POST",
                    headers : { 'Content-Type': 'application/json' },
                    body : JSON.stringify(loc)
                });
            });
        } else {
            const locationDisplay = document.getElementById('location-display');
            locationDisplay.innerHTML = "Geolocation is not available in your browser.";
        }
</script>

Express后端代码

const express = require('express');
const app = express();
app.use(express.json());

app.get('/',(req,res)=>{
    res.sendFile(__dirname + '/index.html');
});

app.post('/',(req,res)=>{
    const result = req.body.loc;  // accessing location
    console.log(result);          
    res.send('My Location : ',result);  // sending location as response
});

app.listen(500,(err)=>{
    if(err)
        console.error(err);
    console.log('Server is listening of port 500');
})

解决方案

问题核心是前端发送的JSON结构与后端预期不匹配:

  • 前端实际发送的是:{latitude: 纬度值, longitude: 经度值}
  • 后端却尝试读取req.body.loc,即预期接收:{loc: {latitude: 纬度值, longitude: 经度值}}

任选以下一种方式修复即可:

方式1:修改前端请求的JSON结构

将地理位置对象嵌套到loc键下,匹配后端预期:

// 修改fetch的body部分
fetch('/',{
    method : "POST",
    headers : { 'Content-Type': 'application/json' },
    body : JSON.stringify({ loc: loc }) // 把loc对象包装在loc键中
});

方式2:修改后端读取逻辑

直接读取req.body中的经纬度数据,去掉不必要的loc层级:

app.post('/',(req,res)=>{
    const result = req.body; // 直接获取整个地理位置对象
    console.log(result);          
    res.send(`My Location : ${JSON.stringify(result)}`); // 用模板字符串拼接响应内容
});

另外注意:原后端代码中res.send('My Location : ',result)会忽略第二个参数,改为模板字符串可以正确返回包含地理位置的响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:08:33