如何通过节点服务器将 JSON 对象写入文件?

How do I write a JSON object to file via Node server?

我在前端使用 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");
});

然后我收到这个错误:

这里是 Node.js 服务器使用 Express.js 框架的示例(如果您不限于 'connect')。

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 中间件。