[英]How to get response from custom api to jade file in Nodejs
我在使用Node.js時遇到問題,我想做的如下。 我有向其發送請求的API。 從API獲得響應后,我想將其發送到index.jade文件。 我已經從我的API得到了響應,但僅在控制台中。 不在我的html文件(index.jade)中。
代碼如下:
app.js
app.get('/', function(req, res) {
var postData = '{'+
' "limit": "10",'+
' "page": 1,'+
' "filters": {'+
' "genre": [],'+
' "region": "",'+
'"prices": 2,'+
' "distance": 31,'+
' "longitude": "4.646219",'+
' "latitude": "52.387388",'+
' "eves": 1,'+
'"from_date": "17-12-2015",'+
'"end_date": "18-12-2014"'+
'}'+
'}';
var options = {
hostname: 'API url',
path: 'api path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunks) => {
console.log(`BODY: ${chunks}`);
var response = JSON.parse(chunks)
res.render('index',{
value: response
});
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body)
console.log(response)
console.log("Successful")
});
玉器
p #{value}
注意:我對Node js還是很陌生。
如果我正確地找到了您,請嘗試如下更改您的代碼。 我發現在不同的回調函數中有相同的req
和res
變量,這會在這里帶來混亂...
因此,我認為可能是同一變量名引起了您的問題,只需將res
之一更改resp
以區分它們,也許可以幫到您。
var req = http.request(options, (resp) => {
var buffer = "";
console.log(`STATUS: ${resp.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(resp.headers)}`);
resp.setEncoding('utf8');
resp.on('data', (chunks) => {
console.log(`BODY: ${chunks}`);
buffer += chunks; // accumulate data here
});
resp.on('end', () => {
console.log('No more data in response.');
res.render('index',{ // send the data received to client
value: buffer // maybe need to JSON.parse(buffer)?
});
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.