2016-06-19 46 views
0

當I型somedomain.com/some_api_url?_var1=1到瀏覽器,該響應是{"1":"descriptive string"},其中1是一個數字索引變量,其值的範圍可以從1n。而「描述性字符串」就是一些總結了索引代表的文字。集成JSON響應轉換的Node.js/Express.js響應

我怎樣才能從somedomain.com/some_api_url?_var1=1 API網址的JSON response集成到下面的非常簡單Node.jsExpress.js例子嗎?

出於測試目的,當用戶從其Web瀏覽器請求http : // localhost : 3000時,下面顯示的非常簡單的app.js返回「Hello World」。需要什麼具體改變如下的代碼來進行,使網頁瀏覽器響應請求用:

Index is: 1 
Description is: descriptive string 

,而不是與「Hello World」的迴應?

這裏是app.js當前代碼:

var express = require('express'); 
var http = require('http'); 
var app = express(); 

app.get('/', function (req, res) { 
    res.send('Hello World!'); 
}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

這裏是我當前的嘗試,這將導致在控制檯打印Got a response: undefined,並與瀏覽器剩下的就掛了,因爲沒有返回給瀏覽器作爲response

var express = require('express'); 
var http = require('http'); 
var app = express(); 

app.get('/', function (req, res) { 

    var url = 'somedomain.com/some_api_url?_var1=1'; 

    http.get(url, function(res){ 
     var body = ''; 

     res.on('data', function(chunk){ 
      body += chunk; 
     }); 

     res.on('end', function(){ 
      var fbResponse = JSON.parse(body); 
      console.log("Got a response: ", fbResponse.picture); 
     }); 
    }).on('error', function(e){ 
      console.log("Got an error: ", e); 
    }); 

}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

get示例代碼改編自the example at this link

回答

1

你實際上忘記了回覆res.send(data)。像這樣改變你的端點代碼。還爲內部響應對象使用不同的變量名稱。我在這裏使用response

app.get('/', function (req, res) { 

    var url = 'somedomain.com/some_api_url?_var1=1'; 

    http.get(url, function(resonse){ 
     var body = ''; 

     resonse.on('data', function(chunk){ 
      body += chunk; 
     }); 

     resonse.on('end', function(){ 
      var body = JSON.parse(body); 
      var text = ''; 
      for (var key in body){ 
        text += 'Index is: ' + key + 
          '\nDescription is: ' + body[key] 
      } 

// The Description is: "descriptive string" 
      console.log("Got a response: ", fbResponse); 
      res.send(text);    
     }); 
    }).on('error', function(e){ 
     console.log("Got an error: ", e); 
    }); 

}); 
+0

您的代碼在瀏覽器中打印'{「1」:「描述性字符串」}'並在控制檯中打印出'響應:undefined'。 OP詢問如何格式化JSON,以便將其轉換爲OP中顯示的簡單HTML輸出。如何改變你的代碼來完成OP的既定目標? – FarmHand

+0

的OP請求瀏覽器打印,在兩行:'指數是:1所 描述爲:描述性string' – FarmHand

+0

@FarmHand這意味着,不存在響應數據沒有畫面屬性。 –

0

試試這個代碼與快遞4.14.0

正如@ Zohaib-Ijaz指出,水庫被重新定義,爲res.send沒有重命名將無法正常工作。此代碼也稱爲自己的演示目的(所以你可以忽略app.get('/some_api_url',目前

然後一旦http.get完成,使用對象和打印,只要你喜歡。請記住這個代碼是不是防禦在JSON的錯誤。

var express = require('express'); 
var http = require('http'); 
var app = express(); 

const PORT = 3000; 

app.get('/', function (req, res) { 

    var url = `http://localhost:${PORT}/some_api_url?_var1=1`; 

    http.get(url, function (resInner) { 
    var body = ''; 

    resInner.on('data', function (chunk) { 
     body += chunk; 
    }); 

    resInner.on('end', function() { 
     var fullResponse = JSON.parse(body); // {"343",:"I've heard 344 is more"} 

     // code to pair the keys with their data in plain js 
     var indexKeys = Object.keys(fullResponse); 
     var replies = indexKeys.map((key) => { 
     return `Index is ${key}\nDescription is ${fullResponse[key]}`; 
     }); 

     //note this injection of a <pre> tag is just so modern browsers 
     // will respect the newlines. it is not an HTML document or JSON 
     res.send(
     `<pre>${replies.join("\n")}</pre>` 
    ); 
    }); 
    }).on('error', function (e) { 
    console.log("Got an error: ", e); 
    }); 

}); 


app.get('/some_api_url', (req, res) => { 
    var var1 = req.query.var1 || "343"; 
    var value = `I've heard ${parseInt(var1) + 1} is more`; 
    var reply = {}; 
    reply[var1] = value; 
    res.send(JSON.stringify(reply)); 
}); 

app.listen(PORT, function() { 
    console.log(`Example app listening on port ${PORT}!`); 
}); 
+0

謝謝。當我完成清潔準備時,我會試試這個。然而,乍一看,你的代碼在響應中打印了一個數組。我們如何改變它以假定第一個變量總是索引值,而第二個變量總是它的描述。這將使更多可用的代碼。 – FarmHand

+0

它不打印數組; res.send()獲取一個字符串。字符串模板將加入的答覆陣列包裝在預標籤中。如果你得到標準的回覆(就像這個快速應用會給出的那樣),這就提出了你在問題中要求的內容。看看地圖如何處理按鍵。請記住,js對象中沒有第一個或第2個。只是鍵和值 – user01

0

你似乎混合了快速,原生HTTP模塊和HTTP客戶端。

這裏是送你正在尋找的響應的服務器端代碼。

var express = require('express'); 
var http = require('http'); 
var app = express(); 

// our "database" 
var database = ['APPLE', 'BOOK', 'CAT', 'DOG', 'ELEPHANT']; 

app.get('/', function (req, res) { 

    // apply query parsing only of the query parameter is specified 
    if ('itemId' in req.query) { 
    var itemId = req.query.itemId; 
    // index less than 0 will not yield anything from our "database" 
    if (itemId < 0) { 
     res.status(400).send('Invalid item id'); 
    // the item index corresponds to one of the items in the "database" 
    } else if (itemId < database.length) { 
     var result = 'Index: ' + itemId + '<br>Description: ' + database[itemId]; 
     res.send(result); 
    // index exceeds the size of the array, so nothing will be found 
    } else { 
     res.status(404).send('Item not found'); 
    } 
    // render the default homepage 
    } else { 
    res.send('Request format: http://localhost:3000/?itemId=n'); 
    } 

}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

要在行動中看到它,請在瀏覽器中加載http://localhost:3000/?itemId=0。有效的itemId值爲0到4.

+0

我不認爲這是OP想要的。 OP想要從服務器進行HTTP GET,處理來自GET的響應,然後返回一組字符串。沒有參數傳遞給根目錄'/' – user01