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

Node.js连接MySQL后,如何在Cordova移动端显示数据库数据?

如何在Cordova应用中展示Node.js获取的MySQL数据

当然可以!你已经搞定了数据库连接和数据查询的核心环节,接下来只需要把Node.js端的数据通过API传递给Cordova前端,就能在移动端展示这些内容了。我给你梳理一下具体的实现步骤:

1. 将Node.js脚本改成HTTP API服务

目前你的代码只是在终端打印数据,Cordova作为客户端无法直接读取终端输出,所以需要把Node.js改成一个简单的HTTP服务器,提供API接口让Cordova请求数据。推荐用Express框架快速搭建:

  • 首先安装依赖:

    npm install express cors
    

    (cors用来处理跨域问题,方便浏览器测试时正常请求)

  • 修改你的db.js代码为API服务:

    const express = require('express');
    const mysql = require('mysql');
    const cors = require('cors');
    const app = express();
    const port = 3000;
    
    // 启用跨域支持
    app.use(cors());
    
    // 数据库连接配置(和你原来的配置一致)
    const con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database: "testdb"
    });
    
    // 定义获取动物列表的API接口
    app.get('/api/animallist', (req, res) => {
      con.connect(err => {
        if (err) {
          console.error('数据库连接失败:', err);
          return res.status(500).json({ error: '无法连接到数据库' });
        }
        
        con.query("SELECT * FROM animallist", (err, result) => {
          if (err) {
            console.error('数据查询失败:', err);
            return res.status(500).json({ error: '查询数据出错' });
          }
          
          res.json(result); // 将查询结果以JSON格式返回给客户端
          con.end(); // 关闭数据库连接
        });
      });
    });
    
    // 启动服务器
    app.listen(port, () => {
      console.log(`API服务已启动,地址:http://localhost:${port}`);
    });
    
  • 运行修改后的文件:

    node db.js
    

    现在你可以在浏览器访问http://localhost:3000/api/animallist,应该能看到JSON格式的动物列表数据了。

2. 在Cordova应用中请求API并渲染数据

接下来需要在Cordova的前端代码里发起HTTP请求,获取数据后渲染到页面上:

  • 首先在www/index.html里添加一个用来展示数据的容器:

    <div>
      <h2>动物列表</h2>
      <ul id="animal-list"></ul>
    </div>
    
  • 然后修改www/js/index.js,在设备就绪后发起请求并渲染数据:

    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
      // 注意:这里不能用localhost,手机无法访问电脑的localhost,要换成电脑在局域网内的IP(比如192.168.1.100)
      const apiUrl = 'http://192.168.1.100:3000/api/animallist';
      
      fetch(apiUrl)
        .then(response => {
          if (!response.ok) throw new Error('请求失败');
          return response.json();
        })
        .then(data => {
          console.log('获取到的数据:', data);
          renderAnimalList(data);
        })
        .catch(error => {
          console.error('获取数据出错:', error);
          alert('无法加载数据,请检查网络连接');
        });
    }
    
    // 把数据渲染到页面的函数
    function renderAnimalList(animals) {
      const listContainer = document.getElementById('animal-list');
      listContainer.innerHTML = ''; // 清空原有内容
    
      animals.forEach(animal => {
        const listItem = document.createElement('li');
        // 这里根据你的数据库表字段修改,比如你的表有name、type等字段
        listItem.textContent = `${animal.name} - ${animal.type}`;
        listContainer.appendChild(listItem);
      });
    }
    

3. 关键注意事项

  • 局域网IP问题:手机和电脑必须在同一个WiFi局域网内,而且API地址要填电脑的局域网IP,不能用localhost。你可以在电脑终端用ipconfig(Windows)或ifconfig(Mac/Linux)查看自己的IP地址。
  • 防火墙设置:确保电脑的防火墙允许3000端口的入站请求,否则手机无法访问API服务。
  • 数据库连接优化:上面的示例每次请求都重新连接数据库,实际项目中建议使用MySQL连接池,避免频繁创建和关闭连接,提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:21:09