簡體   English   中英

使用帶有回調的 http.get Node.js

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

我試圖在這里實現這個庫,它生成二維碼和所有其他類型的代碼。

我遇到的問題是發出一個請求,我可以訪問 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);

問題是我已經創建了一個服務器,我只想在 get 請求中調用庫,而不創建另一個服務器。 我試過了

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

這顯然不起作用,因為回調僅將響應作為參數。

我想在實現中使用裸節點,因為這是我的服務器的實現方式,而且我不想僅為此場景添加庫(如 Express)。

您嚴重誤解了http.get的作用

http.get用於對該特定 url 進行HTTP GET調用。 這基本上是axiosrequestajaxxhrpostmanbrowser所做的。

http.get的 url 參數不是路由。 它實際上是您想要點擊的網址。

如果你想處理特定的路由,你必須在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以獲取您可以使用的可用屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM