node.js - 从 IncomingMessage 获取 url 和正文?

标签 node.js http

我是 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/

相关文章:

javascript - Discord.js 如何切片链接

java - 为 Java HTTP 服务器构建 http header

c - 如何验证网页是否存在

node.js - 在 React 中使用 Apollo.js 将查询映射到 props

php - 使用 Perl 或 PHP 的 HTTP 多部分响应

http - 使用 gzip/deflate 压缩的简单 HTTP 请求

http - 关于Http大文件下载的MD5校验

python - 与 Node.js 服务器应用程序通信

node.js - 当无法在 mongodb node.js 中保存数据时返回哪个 HTTP 状态代码?

javascript - 从引用数组中删除项目( Mongoose )