我对节点很新.我正处于一个简单的服务器,它应该只打印请求查询和它所需的请求体.我所理解的是"句柄请求"函数实际上并不返回请求对象,而是返回一个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/");
Run Code Online (Sandbox Code Playgroud)
请求代码:
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();
Run Code Online (Sandbox Code Playgroud)
请注意,我是一个完整的初学者.我不是在寻找明确的解决方案.
之所以看不到查询字符串,request.url是因为您没有正确发送查询字符串。在您的请求代码中,没有query属性options。您必须将您的querystring附加到path。
path: '/' + '?' + querystring.stringify({argument: 'narnia'}),
Run Code Online (Sandbox Code Playgroud)
对于第二个问题,如果要使用完整的请求正文,则必须像流一样读取请求对象。
var server = http.createServer(function (request, response) {
request.on('data', function (chunk) {
// Do something with `chunk` here
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6110 次 |
| 最近记录: |