我是 Node 的新手。我现在有一个简单的服务器,它应该只打印请求 query 和它需要的请求 body 。据我了解,“处理请求”函数实际上不返回一个请求对象,而是一个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();
请注意,我是一个完全的初学者。我不是在寻找仅限 express 的解决方案。
最佳答案
您在 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 获取 url 和正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599473/