我是Node的新手。我现在有一个简单的服务器,应该只打印请求查询和请求正文即可。我了解的是,“处理请求”功能实际上并不返回请求对象,而是IncomingMessage
对象。
我不了解两件事:如何获取查询字符串和正文。
我只得到路径,没有查询并且未定义主体。
服务器代码:
var http = require('http');
var server = http.createServer(function (request, response) {
console.log("Request query " + request.url);
console.log("Request body " + request.body);
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
请求代码:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
query: "argument=narnia",
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('response: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<h1>Hello!</h1>");
req.end();
请注意,我是一个完整的初学者。我不是在寻找仅表达的解决方案。
最佳答案
之所以在request.url
上看不到查询字符串,是因为您没有正确发送一个查询字符串。在您的请求代码there is no query
property of options
中。您必须append your querystring to the path
。
path: '/' + '?' + querystring.stringify({argument: 'narnia'}),
对于第二个问题,如果要使用完整的请求正文,则必须像流一样读取请求对象。
var server = http.createServer(function (request, response) {
request.on('data', function (chunk) {
// Do something with `chunk` here
});
});
关于node.js - 从IncomingMessage获取网址和正文?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24599473/