在Node.js中创建HTTP回显服务器

4
我需要做的是一个简单的Node.js HTTP回显服务器。然而,我在Node网站和其他一些地方找到的服务器要么不按我的意愿工作,要么我不理解它们的工作方式。
我使用了这个简单的回显服务器,但在我的客户端(用Java编写)上,我没有得到想要的结果。
var http = require('http');

http.createServer(function(request,response){

 response.writeHead(200);
 request.pipe(response);

}).listen(8080);

我希望我的服务器能够生成包括响应头和响应体的响应,其中我将获得客户端发送并返回的整个HTTP请求。客户端测量从发送请求到收到完整响应的时间。客户端还将响应主体写入文件。
当我尝试使用类似以下代码的东西时:
 response.write(request.url);

我在响应正文中获取了request.url,并且它可以工作,但我希望得到整个HTTP请求。

任何帮助都将不胜感激。


Node.js指南展示了如何实现这一点 https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction - Ronnie Royston
5个回答

1

使用:

response.write(JSON.stringify(request.headers))

0
这是一个示例回显服务器,除了回显主体外,还记录请求方法、URL、标头和主体,并提供必要的CORS配置以正确处理预检请求。

服务器

const http = require("http");
const port = 8080;

http
  .createServer((req, res) => {
    const headers = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "OPTIONS, POST, GET, PUT",
      "Access-Control-Max-Age": 2592000, // 30 days
      "Access-Control-Allow-Headers": "*",
      /** add other headers as per requirement */
    };

    if (req.method === "OPTIONS") {
      res.writeHead(204, headers);
      res.end();
      return;
    }

    if (["GET", "POST", "PUT"].indexOf(req.method) > -1) {
      res.writeHead(200, headers);
      let body = [];
      req.on('data', (chunk) => {
        body.push(chunk);
      }).on('end', () => {
        body = Buffer.concat(body).toString();
        console.log(`==== ${req.method} ${req.url}`);
    console.log('> Headers');
        console.log(req.headers);

    console.log('> Body');
    console.log(body);

        res.write(body);
        res.end();
      });
      // res.end("Hello World");
      return;
    }

    res.writeHead(405, headers);
    res.end(`${req.method} is not allowed for the request.`);
  })
  .listen(port);
console.log("listening on port " + port);

使用示例

curl -X PUT -d '{"message": "hello"}' localhost:8080

0
在完成时添加response.end()
http.createServer(function(request,response){

  response.writeHead(200)
  request.pipe(response)
  response.end()

}).listen(8080)

0

HTTP是基于TCP的,因此需要创建一个TCP服务器并进行回显操作。

const net = require('node:net');

const server = net.createServer((socket) => {
    console.clear(); // I like this
    socket.on(`data`, d => {
        socket.write(d);
        console.log(String(d));
    });
    setTimeout(() => {
        socket.end();
    }, 100);
}).on('error', (err) => {
    throw err;
});

server.listen(8080, () => {
    console.log(`opened server on ${server.address().port}`);
}); 

-1

你试图将请求传输到响应中,这是没有意义且不起作用的。我建议你使用connectexpress模块。然后你可以这样做:response.status(200).send("非常棒").end()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接