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

如何用纯Vanilla JS实现无库环境下客户端向服务器传数据并存储至LocalStorage

先明确一个关键误区:服务器端没有LocalStorage

LocalStorage是浏览器客户端专属的存储API,服务器端根本不存在这个东西。你想要的是“服务器端存储客户端发来的数据”,下面给你一套纯原生的实现方案——全程不用任何第三方库,前端用Vanilla JS,后端用Node.js原生模块。

实现方案(纯Vanilla JS + 原生Node.js)

1. 客户端代码(纯浏览器原生JS)

用原生fetch API发送POST请求,把数据传给服务器:

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="dataInput" placeholder="输入要存储的数据">
  <button onclick="sendData()">发送数据</button>

  <script>
    function sendData() {
      const input = document.getElementById('dataInput');
      const data = { content: input.value };

      // 原生fetch发送POST请求
      fetch('/save-data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
      .then(response => response.text())
      .then(message => {
        alert(message);
        input.value = '';
      })
      .catch(error => console.error('发送失败:', error));
    }
  </script>
</body>
</html>

2. 服务器端代码(纯Node.js原生,无第三方库)

用Node.js原生的http(搭建服务器)、fs(文件操作)、path(路径处理)模块实现,把客户端发来的数据存在服务器本地文件里:

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

const server = http.createServer((req, res) => {
  // 返回客户端页面
  if (req.url === '/' && req.method === 'GET') {
    const filePath = path.join(__dirname, 'index.html');
    fs.readFile(filePath, (err, content) => {
      if (err) {
        res.writeHead(500);
        res.end('加载页面失败');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(content, 'utf-8');
      }
    });
  }
  // 接收并存储数据
  else if (req.url === '/save-data' && req.method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        // 把数据追加到服务器本地的data.txt文件
        fs.appendFile('data.txt', JSON.stringify(data) + '\n', (err) => {
          if (err) {
            res.writeHead(500);
            res.end('存储数据失败');
          } else {
            res.writeHead(200);
            res.end('数据已成功存储在服务器');
          }
        });
      } catch (err) {
        res.writeHead(400);
        res.end('无效的JSON数据');
      }
    });
  }
  // 处理404请求
  else {
    res.writeHead(404);
    res.end('页面不存在');
  }
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
运行步骤
  1. 把客户端代码存为index.html,服务器代码存为server.js,放在同一个文件夹里
  2. 打开终端,运行node server.js启动服务器
  3. 浏览器访问http://localhost:3000,输入数据点击发送,服务器会把数据存在同目录下的data.txt文件里
核心说明
  • 全程零第三方依赖:前端用原生DOM API和fetch,后端只用Node.js自带模块
  • 用服务器本地文件存储代替你提到的“服务器LocalStorage”——因为LocalStorage仅属于浏览器环境,服务器端没有这个API

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:27:27