angularjs - 如何通过 Node 服务器将 JSON 对象写入文件?

标签 angularjs json node.js post http-status-code-404

我正在使用 Angular 作为前端,并尝试将 JSON 对象写入与 index.html 位于同一目录中的名为“post.json”的文件中。我可以使用 PHP 使其工作,但我想知道如何使用 Node.js 使其工作。我在网上看了很多帖子,但也许我不明白 http POST 实际上是如何工作的,以及服务器需要从 Angular 应用程序写入文件的设置。如何从 Angular 应用程序写入文件以及 Node 服务器需要哪些设置?

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 = "";
};

这是 Node 服务器文件:

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");
});

然后我收到此错误:

enter image description here

最佳答案

这是使用 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 Controller 中明确指定 url:

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

编辑:

删除了 body-parser 中间件以进行简化。

关于angularjs - 如何通过 Node 服务器将 JSON 对象写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35494990/

相关文章:

javascript - TypeScript 经常出现问题并且更喜欢 import 而不是 require

javascript - stateChangeStart - AngularJS

php - 如何在异步任务上加载图像

javascript - Firebase http 函数在 http 请求库返回数据之前完成

Android登录注册中java.lang.String无法转换为JSONObject

android - 处理来自 JsonReader 的空指针

javascript - 如何使用 Node.js MongoDB 驱动程序插入 long/BigInt?

javascript - angularjs $scope.template 不会改变 View

html - 使用 angularjs 和 HTML 在单击按钮时显示 div

angularjs - 一起使用 angularjs ui bootstrap datepicker 和 timepicker