如何通过节点服务器将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应用程序写入文件以及节点服务器需要哪些设置?
I am using Angular for the front-end and attempting to write a JSON object to a file called 'post.json' in the same directory as index.html. I can make it work using PHP but I want to know how do it with Node.js. I have looked at a lot of posts online but maybe I am not understanding how http POST actually works and what settings the server needs to write to file from an Angular app. How do I write to file from the Angular app and what settings does the node server need?
Angular文件中的代码:
Code in the Angular file:
// 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 框架(以防您不限于连接").
Here is example of Node.js server using Express.js framework (in case you are not limited to '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!');
});
在您的角度控制器中,明确指定网址:
In your angular controller specify explicitly the url:
$http({
url: 'http://localhost:8080',
method: "POST",
data: data,
header: 'Content-Type: application/json'
})
为简化起见,删除了body-parser
中间件.
Removed body-parser
middleware for simplification.
这篇关于如何通过节点服务器将JSON对象写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!