简体   繁体   English

使用带有回调的 http.get Node.js

[英]Use http.get Node.js with callback

I am trying to implement this library here , which generates QR codes and all other kinds of codes.我试图在这里实现这个库,它生成二维码和所有其他类型的代码。

The problem I have is making a request where I have access to both req and res object, since I will need to pass these to the library.我遇到的问题是发出一个请求,我可以访问 req 和 res 对象,因为我需要将它们传递给库。 In the documentation, they are recommending在文档中,他们建议

http.createServer(function(req, res) {
    // If the url does not begin /?bcid= then 404.  Otherwise, we end up
    // returning 400 on requests like favicon.ico.
    if (req.url.indexOf('/?bcid=') != 0) {
        res.writeHead(404, { 'Content-Type':'text/plain' });
        res.end('BWIPJS: Unknown request format.', 'utf8');
    } else {
        bwipjs.request(req, res); // Executes asynchronously
    }

}).listen(3030);

The problem is I already have a server created, and I simply want to call the library in a get request, without creating another server.问题是我已经创建了一个服务器,我只想在 get 请求中调用库,而不创建另一个服务器。 I have tried我试过了

http.get('http://localhost:3030/?bcid=azteccode&text=thisisthetext&format=full&scale=2', (req, res) => {
  bwipjs.request(req, res); // Executes asynchronously
  }
)

which obviously didn't work as the callback only takes response as an argument.这显然不起作用,因为回调仅将响应作为参数。

I would like to use bare node in the implementation as this is the way my server is implemented, and I don't want to add a library (like Express) just for this scenario.我想在实现中使用裸节点,因为这是我的服务器的实现方式,而且我不想仅为此场景添加库(如 Express)。

You are heavily misunderstanding the role of http.get您严重误解了http.get的作用

http.get is used to do HTTP GET call to that certain url. http.get用于对该特定 url 进行HTTP GET调用。 It's basically what axios or request or ajax or xhr or postman or browser does.这基本上是axiosrequestajaxxhrpostmanbrowser所做的。

The url param of http.get is not route. http.get的 url 参数不是路由。 It's literally is the url you want to hit.它实际上是您想要点击的网址。

If you want to handle specific route you have to do it in the http.createServer() handler itself.如果你想处理特定的路由,你必须在http.createServer()处理程序本身中进行。

Like,喜欢,

http.createServer(function(req, res) {
  if (req.url.indexOf('/?bcid=') != 0) {
      //do something
  } else if (req.method == "get" && req.url.indexOf('/?bcid=') != 0){
      bwipjs.request(req, res); // Executes asynchronously
  } else {
    //do something else
  }

}).listen(3030);

Check out the req or http.IncomingMessage for available properties that you can use.查看reqhttp.IncomingMessage以获取您可以使用的可用属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM