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

Node.js新手求助:访问/index.html报错,却能获取MySQL数据

解决Node.js无法访问/index.html但能获取MySQL数据的问题

看起来你的Node.js服务器已经成功配置了/rows/接口来返回MySQL数据,但没有处理静态HTML文件的请求——这就是为什么访问/index.html会得到Cannot GET /index.html的原因。Node.js默认不会自动提供静态文件,需要你手动配置或者添加路由来处理这类请求。

下面分两种常见场景给你解决方案:

场景1:使用Express框架(最常见的情况)

如果你的项目用了Express,只需要两步就能搞定:

  1. 配置静态资源目录
    把你的index.html放在项目根目录下的public文件夹里(没有的话新建一个),然后在服务器代码中添加以下配置,让Express自动处理静态文件请求:

    const express = require('express');
    const app = express();
    
    // 让Express托管public文件夹里的静态资源
    app.use(express.static('public'));
    
    // 保留你的/rows/接口逻辑
    app.get('/rows/', (req, res) => {
        // 这里是你获取并返回MySQL数据的代码
    });
    
    app.listen(3000, () => {
        console.log('Server running on http://localhost:3000');
    });
    

    重启服务器后,访问http://localhost:3000/index.html就能正常加载页面了。

  2. 或者手动添加/index.html路由
    如果你不想用静态资源目录,也可以直接写路由返回HTML文件:

    const path = require('path');
    
    app.get('/index.html', (req, res) => {
        // 用res.sendFile返回HTML,确保路径指向正确的文件位置
        res.sendFile(path.join(__dirname, 'index.html'));
    });
    

    __dirname代表当前脚本所在的目录,确保index.html和你的服务器脚本在同一目录,或者调整路径到正确位置。

场景2:使用原生Node.js(未用框架)

如果是用原生http模块写的服务器,需要在请求处理逻辑中判断路径,手动读取并返回HTML文件:

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
    if (req.url === '/index.html') {
        fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
            if (err) {
                res.writeHead(500, {'Content-Type': 'text/plain'});
                res.end('加载index.html出错');
                return;
            }
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        });
    } else if (req.url === '/rows/') {
        // 保留你的MySQL数据返回逻辑
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify([{"ID":1,"Name":"Wendy Smith","Message":"Hello, how are you?"}]));
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('404 Not Found');
    }
});

server.listen(3000);

额外提醒

  • 确认index.html的文件路径是否正确,避免因路径错误导致无法读取文件。
  • 如果用Express,静态资源中间件express.static要放在其他路由的前面,这样Express会优先处理静态文件请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:20:55