
本文详解 fetch 请求中误用 `json.stringify()` 导致响应对象被转为字符串、进而无法访问 `.features` 等属性的问题,并提供完整、安全的前后端联调方案。
在使用 fetch 调用 Django 提供的 GeoJSON API 时,一个常见但隐蔽的错误是:在已成功解析为 JavaScript 对象后,又将其意外转回 JSON 字符串。这正是你遇到 typeof data === 'string' 且 data.features 为 undefined 的根本原因。
? 问题定位:链式 .then() 中的类型丢失
你的原始代码如下(关键问题行已标出):
fetch('/guidebook/api/peak-data/')
.then(response => response.json()) // ✅ 正确:将响应体解析为 JS 对象(如 { type: "FeatureCollection", features: [...] })
.then(response => JSON.stringify((response))) // ❌ 错误:又把对象转成字符串!此时 response 已是 object,再 stringify → string
.then(data => {
console.log('Type of data:', typeof data); // → "string"
console.log('Type of features:', typeof data.features); // → undefined(字符串无 .features 属性)
});response.json() 返回的是一个 Promise,它解析响应流并返回一个 JavaScript 对象(Object),而非字符串。而 JSON.stringify() 的作用恰恰相反——它把 JS 对象序列化为 JSON 格式的字符串。一旦执行这一步,后续所有属性访问(如 data.features)都会失败。
✅ 正确写法:保持对象形态,直接使用
只需删除冗余的 JSON.stringify() 步骤,即可直接操作解析后的 GeoJSON 对象:
立即学习“前端免费学习笔记(深入)”;
fetch('/guidebook/api/peak-data/')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // 返回 Promise
})
.then(data => {
console.log('Parsed GeoJSON object:', data);
console.log('Type of data:', typeof data); // → "object"
console.log('Features count:', data.features?.length || 0);
// ✅ 安全访问 features(推荐使用可选链)
if (Array.isArray(data.features)) {
data.features.forEach(feature => {
const coords = feature.geometry?.coordinates;
const name = feature.properties?.peak_name;
console.log(`Peak: ${name}, Coordinates:`, coords);
});
}
})
.catch(error => {
console.error('Fetch or parsing failed:', error);
}); ⚠️ 后端注意事项:Django JsonResponse 与 serialize() 的配合
你的 Django 视图存在一个潜在风险:
def get_peak_data(request):
peaks = Peak.objects.all()
peak_data = serialize('geojson', peaks, geometry_field='peak_coordinates')
return JsonResponse(peak_data, safe=False, content_type='application/json')⚠️ serialize('geojson', ...) 返回的是 字符串格式的 GeoJSON(不是 Python dict)。虽然 JsonResponse(..., safe=False) 可接受字符串,但这绕过了 Django 的 JSON 安全校验,且易引发编码/头信息不一致问题。
✅ 推荐更健壮的写法(解析后再返回):
from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder
import json
def get_peak_data(request):
peaks = Peak.objects.all()
# serialize → str → json.loads() → dict → JsonResponse 自动序列化(更安全)
geojson_str = serialize('geojson', peaks, geometry_field='peak_coordinates')
geojson_dict = json.loads(geojson_str) # 转为 Python dict
return JsonResponse(geojson_dict, encoder=DjangoJSONEncoder)或更简洁地(Django 4.1+ 支持直接序列化为 dict):
from django.contrib.gis.serializers.geojson import Serializer
def get_peak_data(request):
peaks = Peak.objects.all()
serializer = Serializer()
geojson_dict = serializer.serialize(
peaks,
geometry_field='peak_coordinates',
use_natural_primary_keys=True,
fields=('peak_name', 'peak_elevation')
)
return JsonResponse(geojson_dict)? 总结:关键原则
- response.json() = 字符串 → JS 对象(只应调用一次);
- JSON.stringify() = JS 对象 → 字符串(仅在需要发送或存储时使用);
- 前端拿到 GeoJSON 对象后,用 data.features、feature.geometry.coordinates 等标准属性访问地理数据;
- 后端避免直接返回 serialize() 的字符串给 JsonResponse,优先确保返回的是 Python 字典结构;
- 始终检查 response.ok 和添加 .catch(),避免静默失败。
遵循以上实践,你就能稳定获取并操作来自 Django 的 GeoJSON 数据,顺利提取坐标、名称等关键字段。










