无数据库时,如何在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:
- The URL format is wrong:
local-host://8080should behttp://localhost:8080 - The
dataparameter has invalid syntax:{ $scope.users }isn't valid JavaScript—you can either pass$scope.usersdirectly or wrap it in a named object - AngularJS's
success()/error()methods are deprecated; usethen()/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.
- Create a
server.jsfile 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}`); }); - Install dependencies in your terminal:
npm install express body-parser - Stop your running
http-serverinstance, then start the new server:
Now your server will serve static files and handle POST requests to save data tonode server.jsdata.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

