在我的应用程序中,我需要将动态数据发布到我的主页面(mani页面意味着如果我在浏览器中运行我的URL(localhost:3456)意味着将在该页面显示一页)。如何发布该数据我试过这个但我无法发布数据。任何人都可以帮我解决问题。
app.js
var http = require('http');
var server = http.createServer(function(req, res){
res.writeHead(200, ['Content-Type', 'text/plain']);
res.write('Hello ');
res.end('World');
});
server.listen(3456);
postdata.js
var data={"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"}
var options = {
host: 'localhost',
port: 3456,
path: '/',
method: 'POST',
data:data,
header: {
'content-type': 'application/json',
'content-length': data.length
}
};
var http=require('http');
var req;
req = http.request(options, function(res) {
var body;
body = '';
res.on('data', function(chunk) {
body += chunk;
});
return res.on('end', function() {
console.log('body is '+body);
});
});
req.on('error', function(err) {
console.log(err);
});
req.write(data);
req.end();
答案 0 :(得分:-1)
你是否已经与Node一起安装了Express,如果是这样你可以设置Rest Api,你可以在jQuery中使用它们并动态绑定数据。请试着调查一下 http://expressjs.com/
希望这有帮助。
答案 1 :(得分:-1)
两件事。第一:
var data={"errorMsg:{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"}
缺少双引号,因此它的语法无效...因此语法高亮显示有问题。
第二
req.write(data);
应该是:
req.write(JSON.stringify(data));
修改强>
根据您的评论,我想您可能会问如何从HTTP POST请求的正文中读取(您的问题是非常含糊不清的措辞)。如果是这样,那么Node.js API中已经有了很好的文档。有点像:
var server = http.createServer(requestHandler);
server.listen(3456);
function requestHandler (req, res) {
req.setEncoding('utf8');
var body = '';
req.on('data', function (chunk) { body += chunk; });
req.on('end', function () {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('The body of your request was: ' + body);
});
}
如果那不是您所要求的,那么您需要澄清您的问题。除非您明确定义它们是什么以及预期结果是什么,否则像“主页”这样的术语没有任何意义。
答案 2 :(得分:-1)
//this is a string
var jsonString = '{"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"}';
//this is an object
var jsonObj = {"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"};
请注意字符串
中的单引号 request.write(chunk, [encoding])
要求chunk为Buffer或string(参见:http://nodejs.org/api/http.html#http_request_write_chunk_encoding)