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

无数据库时,如何在http-server搭建的本地服务存储表单数据?

Hey there! Let's break down how to get your form data stored when using http-server and AngularJS—since http-server is just a static file server, it doesn't handle POST requests out of the box. Here's what you need to fix and implement:

First, Fix Your AngularJS Code

Your current code has a couple of syntax and logical issues:

  1. The URL format is wrong: local-host://8080 should be http://localhost:8080
  2. The data parameter has invalid syntax: { $scope.users } isn't valid JavaScript—you can either pass $scope.users directly or wrap it in a named object
  3. AngularJS's success()/error() methods are deprecated; use then()/catch() instead

Here's the corrected version:

$scope.sendData = function() {
  $http({
    url: 'http://localhost:8080/save-data', // We'll set up this endpoint next
    method: "POST",
    data: $scope.users // Directly pass your form-bound data object
  })
  .then(function(response){
    alert("Data stored successfully");
  })
  .catch(function(error){
    console.error("Error storing data:", error);
    alert("Failed to store data. Check your browser console for details.");
  });
};

Next, Handle POST Requests (Since http-server Can't Do This Alone)

http-server only serves static files—it can't process POST requests or save data. You have two simple solutions:

Option 1: Use a Minimal Node.js Backend (Server-Side Storage)

This lets you save data to a local JSON file, making it persistent across browser sessions.

  1. Create a server.js file in your project root:
    const express = require('express');
    const bodyParser = require('body-parser');
    const fs = require('fs');
    const app = express();
    const port = 8080;
    
    // Serve static files like http-server does
    app.use(express.static('./'));
    // Parse JSON request bodies
    app.use(bodyParser.json());
    
    // Handle POST requests to save data
    app.post('/save-data', (req, res) => {
      // Read existing data (or initialize empty array if file doesn't exist)
      fs.readFile('./data.json', 'utf8', (err, data) => {
        let users = [];
        if (!err) {
          users = JSON.parse(data);
        }
        // Add new form data to the array
        users.push(req.body);
        // Write updated data back to the JSON file
        fs.writeFile('./data.json', JSON.stringify(users, null, 2), (err) => {
          if (err) {
            console.error(err);
            res.status(500).send('Failed to save data');
          } else {
            res.status(200).send('Data saved successfully');
          }
        });
      });
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    
  2. Install dependencies in your terminal:
    npm install express body-parser
    
  3. Stop your running http-server instance, then start the new server:
    node server.js
    
    Now your server will serve static files and handle POST requests to save data to data.json.

Option 2: Use localStorage (Pure Frontend, No Backend)

If you don't need server-side persistence, you can save data directly to the user's browser:
Modify your AngularJS function like this:

$scope.sendData = function() {
  // Get existing data from localStorage (or empty array if none exists)
  let storedUsers = JSON.parse(localStorage.getItem('users')) || [];
  // Add new form data
  storedUsers.push($scope.users);
  // Save back to localStorage
  localStorage.setItem('users', JSON.stringify(storedUsers));
  alert("Data stored successfully in your browser!");
};

Note: This data only lives in the user's browser—other users won't see it, and it'll be cleared if the user clears their browser data.

Final Check: Ensure Form Binding Works

Make sure your HTML form is properly bound to $scope.users:

<form ng-submit="sendData()">
  <input type="text" ng-model="users.name" placeholder="Your Name" required>
  <input type="email" ng-model="users.email" placeholder="Your Email" required>
  <button type="submit">Save Data</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:31:17