HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="controller.js"></script>
<title>Angular</title>
</head>
<body ng-controller="myController">
<p>Price: <input type="number" ng-model="itemAmount" placeholder="Enter the price"/> </p>
<p>Name: <input type="text" ng-model="itemName" placeholder="Enter the itemName"/> </p>
<button type="submit" ng-click="addItem()">Submit</button>
</body >
</html>
控制器
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
$scope.items = [];
$scope.addItem = function() {
$scope.items.push({
amount: $scope.itemAmount,
name: $scope.itemName
});
var data = JSON.stringify($scope.items);
$http({
url: 'http://localhost:8080',
method: "POST",
data: data,
header: 'Content-Type: application/json'
}).then(function(response) {
console.log(response);
}, function(response) {
console.log(response);
});
// Clear input fields after push
$scope.itemAmount = "";
$scope.itemName = "";
};
});
JSON文件
{"items":[]}
NodeJS代码
var express = require('express');
var app = express();
var fs = require('fs');
app.use(express.static('static'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/', function (req, res) {
fs.writeFile(__dirname+"/post.json", req.body, function(err) {
if(err) {
return console.log(err);
}
res.send('The file was saved!');
});
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
我使用了其中一个问题已经问过的代码。话虽如此,我想使用nodejs和angularjs代码更新最初为空花括号的json文件。当我在输入字段中输入并单击提交时,数据应在json文件中得到更新。我想我的控制器代码有问题。请帮忙!!例如,如果我在价格字段中输入23,并在文件名中输入“ apples”,则我的json文件应更新为:
{
"items": [{
"amount": 23,
"name": "apples"
}]
}
控制台中显示的错误:
Failed to load resource: net::ERR_CONNECTION_RESET