首页 > 解决方案 > 使用带有回调的 http.get Node.js

问题描述

我正在尝试在这里实现这个库,它会生成二维码和所有其他类型的代码。

我遇到的问题是发出一个请求,我可以访问 req 和 res 对象,因为我需要将它们传递给库。在文档中,他们推荐

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);

问题是我已经创建了一个服务器,我只想在获取请求中调用该库,而不创建另一个服务器。我努力了

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

这显然不起作用,因为回调只将响应作为参数。

我想在实现中使用裸节点,因为这是我的服务器的实现方式,我不想仅为这种情况添加库(如 Express)。

标签: javascriptnode.jshttp

解决方案


你严重误解了角色的作用http.get

http.get用于对该特定 url进行HTTP GET调用。它基本上就是axiosor requestor ajaxor or or xhror postmanor做什么browser

的 url 参数http.get不是路由。从字面上看,它就是您要访问的网址。

如果要处理特定路线,则必须在http.createServer()处理程序本身中进行。

喜欢,

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);

查看reqhttp.IncomingMessage了解您可以使用的可用属性。


推荐阅读