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

使用Cordova从MySQL数据库获取数据失败求助

问题:Cordova Android应用无法从MySQL获取数据展示

作为学徒程序员,我正在做学习项目,用Cordova开发Android应用,需要实现从MySQL数据库获取数据并展示的功能。目前代码在网页端可正常运行,但App端仅显示标题“Événements :”,页面内容为空,怀疑服务器与App的连接存在问题,希望获得解决方法或替代方案。

代码文件

HTML代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Affichage d'événements</title>
</head>
<body>
<h1>Événements :</h1>
<ul id="evenements-list"></ul>

<script src="hello2.js"></script>
</body>
</html>

Server.js代码

const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');

const app = express();
app.use(cors());

//config link to data base 
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '', // the password is written ;)
    database: '', //same
    charset: 'utf8' // ou un autre encodage approprié
});

//way to get all the events 
app.get('/evenements', (req, res) => {
    connection.query('SELECT * FROM evenements', (err, results) => {
        if (err) {
            console.error('error lors de l\'exécution de la requête :', err);
            return res.status(500).send('Erreur lors de la récupération des événements');
        }

        console.log('Événements :', results); // Ajouter cette ligne pour afficher les résultats

        res.json(results);
    });
});

// Démarrer le serveur
app.listen(3000, () => {
    console.log('Serveur en écoute sur le port 3000');
});

hello.js代码

//function which displays the events on the html page
function afficherDetailsEvenement(evenement) {
    const { id, titre, localisation, meteo, description } = evenement;

    const ulElement = document.getElementById('evenements-list');
    const liElement = document.createElement('li');
    liElement.innerHTML = `
        <p>ID: ${id}</p>
        <p>Titre: ${titre}</p>
        <p>Localisation: ${localisation}</p>
        <p>Météo: ${meteo}</p>
        <p>Description: ${description}</p>
    `;
    ulElement.appendChild(liElement);
}

// recuperation of the elements with fetch 
fetch('http://localhost:3000/evenements') //Or with the ip adress
    .then(response => response.json())
    .then(data => {
        const evenements = data;
        console.log('Événements :', evenements);

        evenements.forEach(evenement => {
            afficherDetailsEvenement(evenement);
        });
    })
    .catch(error => {
        console.error('errorlors de la récupération des événements :', error);
    });

已尝试的方法

  • 修改代码细节,结果不变;
  • 在Cordova的config.xml中添加规则:
<access origin="*" />
<allow-navigation href="http://*/*" /> //with the adress of 
<allow-navigation href="https://*/*" />
  • 更换端口;
  • 尝试显示事件数量,App端无任何显示;
  • 下载Cordova插件。

解决方法与替代方案

1. 修正服务器地址问题

App中的localhost指向的是Android设备自身,而非你的开发电脑。需要:

  • 找到开发电脑的局域网IP(Windows用ipconfig,Mac/Linux用ifconfig);
  • 将hello.js中的fetch地址替换为该IP:fetch('http://192.168.x.x:3000/evenements');
  • 修改server.js的监听配置,让服务器允许外部设备访问:
app.listen(3000, '0.0.0.0', () => {
    console.log('Serveur en écoute sur le port 3000, accessible depuis le réseau');
});
  • 确保开发电脑和Android设备连接在同一个局域网下。

2. 完善Cordova权限配置

  • 确保安装了cordova-plugin-whitelist插件,执行命令:
cordova plugin add cordova-plugin-whitelist
  • 在config.xml中补充完整的权限规则:
<access origin="*" />
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

3. 调试App网络请求

用Chrome远程调试工具(打开chrome://inspect)连接你的Android设备,查看App的Console日志,确认fetch请求的错误类型(比如连接超时、CORS错误、404等),精准定位问题。

4. 替代方案:本地数据存储

如果不想依赖外部服务器,可以:

  • 使用cordova-plugin-sqlite-2插件在App内创建本地SQLite数据库,将MySQL的数据同步到本地后再展示;
  • 或者将静态数据打包成JSON文件放在App的www目录下,直接读取本地文件展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:52:30