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

如何在客户端client.js中调用Node.js编写的_api.js里的addUser函数?

问题原因及解决方案

你遇到的核心问题是:客户端浏览器环境和Node.js后端环境完全独立,无法直接导入Node.js模块。浏览器既不支持Node.js的require语法,也没有权限访问fs这类Node.js专属的文件系统API,必须通过HTTP请求让前后端通信来实现功能。

正确实现步骤

1. 搭建Node.js后端服务(处理用户添加逻辑)

首先需要把你的_api.js改成一个HTTP接口,这里用Express框架举例(先执行npm install express cors安装依赖):

// server.js
const fs = require('fs')
const express = require('express')
const cors = require('cors')
const app = express()
const port = 3000

// 解决跨域问题
app.use(cors())
// 解析JSON格式的请求体
app.use(express.json())

const databasePath = "./database/db.json" // 注意使用相对路径,确保文件存在

// 定义添加用户的接口
app.post('/api/addUser', (req, res) => {
  const user = req.body

  fs.readFile(databasePath, (err, content) => {
    if (err) {
      return res.status(500).json({ success: false, msg: '读取数据库失败' })
    }

    const DATABASE = JSON.parse(content)
    const USERS = DATABASE.users

    DATABASE.amount += 1
    USERS[`${DATABASE.amount}`] = {
      name: user.name,
      password: user.password,
    }

    fs.writeFile(databasePath, JSON.stringify(DATABASE), (err) => {
      if (err) {
        return res.status(500).json({ success: false, msg: '写入数据库失败' })
      }
      res.json({ success: true, msg: '用户添加成功' })
    })
  })
})

// 启动服务器
app.listen(port, () => {
  console.log(`后端服务运行在 http://localhost:${port}`)
})

2. 修改客户端代码(通过请求调用后端接口)

把client.js改成用fetch发送HTTP请求,而不是直接导入Node.js函数:

const username = document.querySelector("#username")
const password = document.querySelector("#password")
const submit = document.querySelector("#submit")

submit.addEventListener('click', async (e) => {
  e.preventDefault() // 阻止表单默认提交行为
  const user = {
    name: username.value,
    password: password.value
  }

  try {
    const response = await fetch('http://localhost:3000/api/addUser', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(user)
    })
    const result = await response.json()
    console.log(result)
    alert(result.msg)
  } catch (err) {
    console.error('请求出错:', err)
    alert('添加用户失败')
  }
})

3. 运行流程

  1. 先启动后端服务:node server.js
  2. 在浏览器中打开前端页面,输入用户名密码后点击提交,客户端就会通过HTTP请求调用后端的添加用户接口

为什么原来的方法行不通?

  • require是Node.js的CommonJS模块语法,浏览器环境没有这个函数,所以会报错
  • fs模块是Node.js专属的文件系统API,浏览器出于安全限制,不允许直接访问本地文件
  • 前后端是两个独立的运行环境,必须通过网络请求(HTTP/HTTPS)来传递数据和调用功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:05:21