簡體   English   中英

將JSON URL數據傳遞到Node.js中的.ejs視圖

[英]Passing JSON URL data to .ejs view in Node.js

我有一個正在運行的小型Node.js應用程序,該應用程序向包含當前天氣預報的URL發出請求,並且我可以成功地控制台記錄JSON數據,但是仍然無法將這些數據傳遞給.ejs視圖? 例如,僅提取溫度或天氣條件,以便可以在div中顯示它? 一直在通過Google搜索,但沒有成功! 我在下面包括了我的index.js文件和index.ejs文件。 提前致謝!

var express = require('express');
var request = require('request');
var app = express();
app.set('view engine', 'ejs');

const url = 'http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=3a3188bfc5bb7c5d2eff1a4985214289'

request(url, (error, response, body)=> {
if (!error && response.statusCode === 200) {
const info = JSON.parse(body)
console.log("Temp: ", info)
} else {
console.log("Got an error: ", error, ", status code: ", response.statusCode)
}

app.get('/', function(req, res){
res.render('index', {info});
});

});

app.listen(8010);
console.log('8010 is the running port');


<!DOCTYPE html>
<html lang="en">
  <body class="container">

    <header>
      <% include ../partials/header %>
    </header>

    <main>
      <div class="jumbotron">
        <% info.main.temp %>
      </div>
    </main>

    <footer>
     <% include ../partials/footer %>
    </footer>
  </body>
</html>

您應該反轉嵌套-換句話說,將請求發送到請求偵聽器主體中的weather API。 這樣,每次有人請求索引頁面('/')時,該頁面將填充最新的天氣:

var express = require('express');
var request = require('request');
var app = express();
app.set('view engine', 'ejs');

const url = 'http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=3a3188bfc5bb7c5d2eff1a4985214289';

app.get('/', function(req, res) {
  request(url, function(error, response, body) {
    const info = JSON.parse(body);
    res.render('index', { info });
  });
});

您正在模板中執行javascript,但未將輸出返回到HTML字符串:

<main>
  <div class="jumbotron">
    <%# this runs javascript %>
        <% info.main.temp %>
    <%# this returns an HTML string %>
        <%= info.main.temp %>
  </div>
</main>

從文檔:

您會注意到<%%>標記內的所有內容都已執行,並且<%=%>標記內的所有內容都將自身插入返回的HTML字符串中。

http://www.embeddedjs.com/getting_started.html

您可以嘗試以下方法:

server.js中的代碼

   var express = require('express');
var app = express();
var info = {
    key: "value",
    key1: "value1",
    key2: "value2",
    key3: "value3"
};
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
    res.render('index', {
        info: info
    });
});
app.listen(3000);

代碼index.ejs:

<html>
    <% if(locals.info){ %>   
      <script type='text/javascript'>
      window.infoObject =<%-JSON.stringify(info)%>;
       console.log( window.infoObject);
   </script>
    <%}%>
    <body>
        <div> <% if(locals.info){ %> 
      <%=JSON.stringify(info)%>;
      <%=info.key%>;
 <%}%></div>
    </body>
</html>

暫無
暫無

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

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