【问题标题】:How do I write a JSON object to file via Node server?如何通过 Node 服务器将 JSON 对象写入文件?
【发布时间】: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


【解决方案1】:

这是使用 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!');
});

在您的角度控制器中明确指定网址:

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

编辑:

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

【讨论】:

  • 这行得通,我只是添加了res.sendFile(__dirname + '/index.html'); 而不是res.send('Hello World!');,然后创建了一个名为 static 的文件夹,其中包含我所有的静态文件,然后将此 app.use(express.static('static')); 添加到 node.js 服务器文件中。谢谢。看起来很干净。
猜你喜欢
  • 2011-04-24
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2016-01-30
相关资源
最近更新 更多