如何将http请求保存到文件?我正在使用Node.js作为服务器。我通过ajax发送数据,如下所示:
我使用fs模块和流,但完全没有起作用,“info.txt”在与服务器代码相同的目录中。
有人能帮帮我吗?
user_info =
{
system_info: [
{'browesr': browser},
{'brower-version': version},
{'cookies': cookieEnabled},
{'os': os},
{'os-version': osVersion}
]
}
}
$.ajax({
url: 'http://127.0.0.1:4560',
data: {"info" : JSON.stringify(user_info)},
type: 'POST',
jsonCallback: 'callback',
success: function(data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('success');
},
error: function(xhr, status, error) {
console.log('Error:' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
POST方法正常工作,在服务器端也接收到了数据。我的问题是如何保存数据!我搜索并找到了一些关于流的内容。这是我的Node.js服务器代码。
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
console.log('Request Received');
res.writeHead(200, {
'Context-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
req.on('data', function (chunk) {
var rstream = fs.createReadStream(JSON.parse(chund));
var wstream = fs.createWriteStream('info.txt');
rstream.pipe(wstream);
str += chunk;
console.log('GOT DATA');
});
res.end('{"msg": "OK"}');
}).listen(4560, '127.0.0.1');
console.log('Server running at http://127.0.0.1:4560/');
我使用fs模块和流,但完全没有起作用,“info.txt”在与服务器代码相同的目录中。
有人能帮帮我吗?
data: JSON.stringify({"info" : user_info})
并设置contentType: "application/json"
。 - dan