我如何写一个JSON对象通过节点服务器文件?

我正在使用Angular作为前端,并尝试将JSON对象写入与index.html相同的目录中名为“post.json”的文件。 我可以使它使用PHP,但我想知道如何与Node.js。 我在网上看了很多post,但也许我不了解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"); }); 

我然后得到这个错误:

在这里输入图像描述

这里是使用Express.js框架的Node.js服务器的例子(如果你不限于“连接”)。

 var express = require('express'); var app = express(); var fs = require('fs'); app.get('/', function (req, res) { res.send('Hello World!'); }); 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!'); }); 

在你的angular度控制器明确指定的url:

  $http({ url: 'http://localhost:8080', method: "POST", data: data, header: 'Content-Type: application/json' }) 

编辑:

为了简化,删除了body-parser中间件。