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

如何在localhost:8000网页集成Node.js文件读取?解决require未定义错误

问题原因

你直接把Node.js专属的服务器端代码放到了前端浏览器环境中执行——require是Node.js的模块加载语法,fs模块是Node.js提供的服务器端文件操作API,浏览器环境既不支持require,也不允许前端JS直接访问服务器文件系统,这就是报错的根本原因。

解决方法

需要通过「后端接口+前端请求」的方式实现文件读取,具体步骤如下:

1. 搭建Node.js后端服务(以Express为例)

因为你已经安装了Node.js,直接按以下步骤操作:

  • 初始化项目并安装Express:
    npm init -y
    npm install express
    
  • 创建server.js文件,编写后端接口:
    const express = require('express');
    const fs = require('fs');
    const app = express();
    const port = 3000;
    
    // 处理跨域(如果前端运行在localhost:8000)
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', 'http://localhost:8000');
      res.header('Access-Control-Allow-Methods', 'GET');
      next();
    });
    
    // 定义读取文件的接口
    app.get('/get-locations', (req, res) => {
      try {
        const contents = fs.readFileSync('./locations.txt', 'utf-8');
        const locations = contents.split(/\r?\n/);
        res.json(locations);
      } catch (error) {
        res.status(500).json({ error: '文件读取失败' });
      }
    });
    
    app.listen(port, () => {
      console.log(`后端服务运行在 http://localhost:${port}`);
    });
    

2. 启动后端服务

在终端执行:

node server.js

3. 修改前端JS代码,通过接口获取数据

把原来直接调用fs的代码替换为前端请求:

window.onload = async function() {
  try {
    // 请求后端接口获取文件内容
    const response = await fetch('http://localhost:3000/get-locations');
    const locations = await response.json();
    console.log(locations); // 👉️ ['One', 'Two', 'Three', 'Four']
    // 这里可以添加数据渲染等后续逻辑
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

可选:前后端一体化部署(无需跨域)

如果想把前端和后端部署在一起,避免跨域问题:

  • 在项目根目录创建public文件夹,把你的前端HTML/CSS/JS文件全部放进去
  • 修改server.js,添加静态文件托管:
    // 托管public文件夹下的静态资源
    app.use(express.static('public'));
    
  • 之后直接访问http://localhost:3000就能打开前端页面,请求接口时只需写/get-locations即可:
    const response = await fetch('/get-locations');
    

内容的提问来源于stack exchange,提问作者displayName is undefined

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:36:26