[英]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字符串中。
您可以尝试以下方法:
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.