【发布时间】:2016-05-31 10:00:57
【问题描述】:
我在前端使用 Angular,并尝试将 JSON 对象写入与 index.html 位于同一目录中的名为“post.json”的文件中。我可以使用 PHP 使其工作,但我想知道如何使用 Node.js。我在网上查看了很多帖子,但也许我不了解 http POST 的实际工作原理以及服务器需要从 Angular 应用程序写入文件的设置。如何从 Angular 应用程序写入文件以及节点服务器需要哪些设置?
Angular 文件中的代码:
// Add a Item to the list
$scope.addItem = function () {
$scope.items.push({
amount: $scope.itemAmount,
name: $scope.itemName
});
var data = JSON.stringify($scope.items);
$http({
url: 'post.json',
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 = "";
};
这是节点服务器文件:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
fs = require('fs');
fs.open('post.json', 'w', function(err, fd){
if(err){
return console.error(err);
}
console.log("successful write");
});
然后我收到此错误:
【问题讨论】:
-
您自己设置了服务器吗?设置路线,是吗?
-
听起来就是我需要的。我会调查一下,谢谢。
标签: angularjs json node.js post http-status-code-404