调用Django API后fetch返回数据转为字符串,无法访问features字段求助
问题原因分析
核心问题出在前端代码的处理流程:
response.json()已将后端返回的JSON响应解析为JavaScript对象- 后续调用的
JSON.stringify(response)又把该对象重新转换为JSON字符串 - 最终
data是字符串类型,字符串不存在.features属性,因此输出undefined
修复方案
1. 前端代码关键修复
直接移除JSON.stringify()步骤,让data保持为JavaScript对象:
fetch('/guidebook/api/peak-data/') .then(response => response.json()) // 移除这一行:.then(response => JSON.stringify((response))) .then(data => { console.log('Raw JSON data:', data); console.log('Type of data:', typeof data); console.log('Type of features:', typeof data.features); // 现在可正常提取坐标属性,示例: if (data.features) { data.features.forEach(feature => { console.log('山峰坐标:', feature.geometry.coordinates); }); } }) .catch(error => { console.log('Error:', error); });
2. 后端代码优化(可选)
Django的serialize('geojson')返回JSON格式字符串,用HttpResponse返回更合适,避免重复序列化:
from django.http import HttpResponse def get_peak_data(request): peaks = Peak.objects.all() peak_data = serialize('geojson', peaks, geometry_field='peak_coordinates') return HttpResponse(peak_data, content_type='application/json')
验证效果
修复后控制台应输出:
Type of data: object Type of features: object
此时可正常访问data.features数组,提取每个元素的geometry.coordinates坐标属性。
内容的提问来源于stack exchange,提问作者Lorteau Erwan
相关产品推荐
相关产品推荐

