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

Node.js搭建http服务访问/api路径无法加载数组数据到页面问题排查

问题根因及修复方案

核心错误

你错误混用了Node.js fs模块的同步读取API和异步回调写法:
fs.readFileSync() 是同步读取方法,执行后直接返回读取到的文件内容,不支持传入回调函数。你写在回调内的设置响应头、返回JSON数据的逻辑完全不会触发,访问/api接口时请求会一直处于挂起状态,自然拿不到数据渲染页面。

其他检查项

  • 确认代码顶部已经引入了http和fs核心模块,否则会抛出未定义报错
  • 确认${__dirname}/starter/dev-data/data.json文件路径与你本地项目结构匹配,避免读取文件时报路径不存在错误

修复代码示例

两种修复方案二选一即可:

方案1:保持同步读取写法,删除回调

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
    const pathName = req.url;
    if(pathName === '/' || pathName === '/overview') {
        res.end('This is the overview');
    } else if (pathName === '/product') {
        res.end('This is the product');
    } else if (pathName === '/api') {
        // 同步读取直接拿返回值,不需要回调
        try {
            const data = fs.readFileSync(`${__dirname}/starter/dev-data/data.json`, 'utf-8');
            res.writeHead(200, { 'Content-type': 'application/json'})
            res.end(data);
        } catch (err) {
            res.writeHead(500, { 'Content-type': 'application/json'})
            res.end(JSON.stringify({msg: '读取数据失败'}))
        }
    } else {
        res.writeHead(404, {
            'Content-type': 'text/html',
            'my-own-header': 'hello-world'
        });
        res.end('<h1>Page not found</h1>');
    }
});

server.listen(8000, '127.0.0.1', () => {
    console.log('Listening to requests on port 8000');
});

方案2:改用异步读取API fs.readFile(),保留回调逻辑

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
    const pathName = req.url;
    if(pathName === '/' || pathName === '/overview') {
        res.end('This is the overview');
    } else if (pathName === '/product') {
        res.end('This is the product');
    } else if (pathName === '/api') {
        // 改用异步readFile方法,回调逻辑正常执行
        fs.readFile(`${__dirname}/starter/dev-data/data.json`, 'utf-8', (err, data) => {
            if(err) {
                res.writeHead(500, { 'Content-type': 'application/json'})
                return res.end(JSON.stringify({msg: '读取数据失败'}))
            }
            res.writeHead(200, { 'Content-type': 'application/json'})
            res.end(data);
        });
    } else {
        res.writeHead(404, {
            'Content-type': 'text/html',
            'my-own-header': 'hello-world'
        });
        res.end('<h1>Page not found</h1>');
    }
});

server.listen(8000, '127.0.0.1', () => {
    console.log('Listening to requests on port 8000');
});

验证方式

修复后重启服务,访问http://127.0.0.1:8000/api,确认能正常返回JSON数据后,前端渲染逻辑即可正常拿到数组数据加载到页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:09:00