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

Python Web应用:MongoDB后端数据无法传递至前端DOM显示求助

解决CherryPy后端数据无法传递到前端DOM的问题

看起来你已经完成了数据获取的核心步骤,问题主要出在后端接口的暴露配置和前端请求的处理逻辑上,咱们一步步来修复:

后端代码修正点

首先你的toshow方法缺少关键的@cherrypy.expose装饰器,CherryPy根本不会把这个方法暴露成可访问的接口!另外全局data变量会导致多次请求时数据重复累加,还有一些小的配置优化:

import cherrypy
import os.path
from pymongo import MongoClient
from bson import json_util

cherrypy.config.update({'server.socket_port': 3000})

class Dbextractor(object):
    @cherrypy.expose
    def index(self):
        return open('index.html')

    @cherrypy.expose  # 必须添加这个装饰器,接口才能被前端访问
    @cherrypy.tools.json_out()
    def toshow(self):
        # 将data移到方法内部,避免全局变量导致数据重复累加
        data = []
        client = MongoClient('mongodb://localhost:27017')
        admin = client.stock_data
        cursor = admin.col.find({})
        for document in cursor:
            data.append(document)
        # 可以返回整个数据集,也可以按需求返回单个文档(比如data[0])
        return data

    @cherrypy.expose
    def shutdown(self):
        cherrypy.engine.exit()

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd()),
            # 添加静态文件目录配置,确保index.html和前端JS能被正确加载
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        },
        '/toshow': {
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'application/json')],
        }
    }
    webapp = Dbextractor()
    cherrypy.quickstart(webapp, '/', conf)

前端代码修正点

你的Request构造函数参数顺序错误,而且fetch返回的是Response对象,需要先解析成JSON才能拿到实际数据,最后还要把数据渲染到DOM中:

// 修正fetch的请求格式
fetch('/toshow', { method: 'GET' })
  .then(response => {
    // 先检查响应是否成功
    if (!response.ok) {
      throw new Error('请求失败,请检查后端服务');
    }
    // 将响应体解析为JSON格式数据
    return response.json();
  })
  .then(data => {
    console.log('成功获取的数据:', data);
    // 把数据渲染到DOM,假设页面有个id为data-container的容器
    const container = document.getElementById('data-container');
    if (container) {
      // 示例:遍历数据生成列表项(根据你的文档字段调整)
      const list = document.createElement('ul');
      data.forEach(item => {
        const listItem = document.createElement('li');
        listItem.textContent = `股票名称:${item.SC_NAME}`;
        list.appendChild(listItem);
      });
      container.appendChild(list);
    }
  })
  .catch(error => {
    console.error('请求过程出错:', error);
  });

额外注意事项

  1. 确保你的index.html中存在用于展示数据的容器,比如:
<div id="data-container"></div>
<script src="你的前端JS文件名.js"></script>
  1. 确认MongoDB服务已启动,stock_data数据库和col集合存在且包含数据。
  2. 重启CherryPy服务后,访问http://localhost:3000即可看到数据渲染到页面上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:10