简体   繁体   English

如何使用Express.JS在Web服务的请求中显示/获取数据?

[英]How can I display/get data in a request from a web-service using Express.JS?

I am using Express.JS to create a web application to serve up some data from a two different web-services and present it in a view (I am using EJS to render my templates). 我正在使用Express.JS创建一个Web应用程序,以服务来自两个不同Web服务的一些数据并将其显示在视图中(我正在使用EJS呈现我的模板)。

GET /ws/breaches?index=[a positive integer] - This webservice returns an object with a "result" property containing an array of at most 20 breached sites, starting at the provided index (eg calling /ws/breaches?index=0 will return the 20 last breached sites, /ws/breaches?index=20 the 20 next, etc.) - A breached site object contains the following information: - site: The domain of the breached site - date: The time of the breach, in milliseconds - number: The number of accounts leaked GET / ws / breaches?index = [正整数]-此Web服务返回具有“结果”属性的对象,该对象包含从提供的索引开始的最多20个违规站点的数组(例如,调用/ ws / breaches?index = 0将返回最后20个被破坏的站点,/ ws / breaches?index = 20将返回20个下一个,等等。)-一个被破坏的站点对象包含以下信息:-site:被破坏站点的域-日期:违约,以毫秒为单位-数字:泄漏的帐户数

GET /ws/icon?site=[domain of a site] - This webservice returns the url of an icon for the provided site - The icons size is 58x36 pixels GET / ws / icon?site = [站点域]-此Web服务返回所提供站点的图标的url-图标大小为58x36像素

app.js app.js

var express = require('express'),
    reload = require('reload'),
    app = express();

app.set('port', process.env.PORT || 8888);

app.use(require('./routes/index'));
app.use(express.static('app/public'))

app.set('view engine', 'ejs');
app.set('views', 'app/views');

var server = app.listen(app.get('port'), function(){
    console.log('Listening on port ' + app.get('port'));
});

reload(server, app);

module.exports = app;

index.js index.js

var express = require('express');
    router = express.Router(),
    connect = require('connect'),
    urlParse = require('url').parse,
    fs = require('fs');

var iconList = fs.readFileSync('app/data/icons.list').toString().split('\n').filter(function(site){
    return site;
});

var random = function(max){
    return Math.floor(Math.random() * max);
};

var icon2Site = function(icon){
    var site = icon.replace(/_/g,'.').replace(/\.png$/,'');
    return site;
};

var breaches = [];

// breaches generation
(function(){
    for(var i =0; i< 1000; i++){
        var index = random(iconList.length);
        breaches.push({
            site : icon2Site(iconList[index]),
            date : Date.now() - 432000000 + random(432000000),
            number : random(100000)
        });
    }
})();

breaches.sort(function(a,b){
    return a.date - b.date;
});

var jsonResponse = function(res, code, body){
    res.writeHead(code, {
        'Content-Type' : 'application/json',
        'Content-Length' : Buffer.byteLength(body)
    });
    res.end(body);
};

var server = connect()
    .use(connect.logger('dev'))
    .use(function(req,res,next){
        req.parsedUrl = urlParse(req.url, true);
        next();
    })
    .use(function(req,res,next){
        if(req.parsedUrl.pathname !== '/ws/breaches'){
            return next();
        }
        var index = parseInt(req.parsedUrl.query.index, 10) || 0;
        jsonResponse(res,200,JSON.stringify({
            result : breaches.slice(index, index + 20)
        }));
    })
    .use(function(req,res,next){
        if(req.parsedUrl.pathname !== '/ws/icon'){
            return next();
        }
        var site = req.parsedUrl.query.site || "";
        console.log(req.parsedUrl.query.site);
        site = site.replace(/\./g,'_') + ".png";
        jsonResponse(res,200,JSON.stringify({
            result : "https://s3-eu-west-1.amazonaws.com/static-icons/" + site
        }));
    })
    .use(connect.static(__dirname + '/public', {
        maxAge : 1000 * 60 * 5 // Five minutes of cache
    }));


router.get('/', function(req, res) {
  res.render('index', {server : server, sidebar:['/images/vertbar.jpg']} );
  console.log(breaches);
});

module.exports = router;

index.ejs index.ejs

<div class="col-xs-12 col-sm-8 col-md-9 col-lg-9 right-column-augment">
  <ul>
    <% /* %> <% for(var i=0; i<tbd.length;i++){%> <% */ %>
      <li><img src="<%= sidebar %>"></li>
    <% /* %> <%}%> <% */ %>
  </ul>
 </div>

Essentially I am unclear how to expose these functions to my routes so I can eventually render in my templates. 本质上,我不清楚如何将这些功能公开给我的路线,以便最终可以在模板中进行渲染。

Thanks in advance! 提前致谢!

Just execute all of the logic of your functions inside the route, then store result in some object, and pass it to EJS view 只需在路由内执行函数的所有逻辑,然后将结果存储在某个对象中,然后将其传递给EJS视图

Example to passing breaches array to your breaches(.ejs) view: 将违规数组传递到违规(.ejs)视图的示例:

    var breaches = [];

// breaches generation
(function(){
    for(var i =0; i< 1000; i++){
        var index = random(iconList.length);
        breaches.push({
            site : icon2Site(iconList[index]),
            date : Date.now() - 432000000 + random(432000000),
            number : random(100000)
        });
    }
})();

breaches.sort(function(a,b){
    return a.date - b.date;
}); 

res.render('breaches', { breaches: breaches });
    return;

In this example, you are adding breaches to your array, then you are sorting then you are passing them to your view called breaches(.ejs) 在此示例中,您要向数组中添加违规,然后进行排序,然后将其传递给称为违规(.ejs)的视图

Then you can loop through them in your breaches(.ejs) view: 然后,您可以在违反(.ejs)视图中遍历它们:

    <div class="col-xs-12 col-sm-8 col-md-9 col-lg-9 right-column-augment">
  <ul>
   <% for(var i = 0; i < breaches.length; i++){ %>
      <li><%= breaches[i].site %></li>
   <% } %>
  </ul>
 </div>

So, it looks like you want to fetch that data client side via ajax. 因此,您似乎想通过ajax获取该数据客户端。 All index.ejs is doing is building an html response on your server, and passing that to the browser. index.ejs所做的全部工作就是在您的服务器上构建html响应,并将其传递给浏览器。 Since all of this is happening on your server, it doesn't make sense (and isn't possible) to make http requests from your view (index.ejs) to get that data. 由于所有这些都是在您的服务器上发生的,因此从您的视图(index.ejs)发出http请求以获取该数据是没有意义的(也是不可能的)。 You could fetch that data in your "router.get('/', function(req, res) {" function and pass the result as variables to your view like you are doing with the sidebar var, but that doesn't seem to be what you are asking for. 您可以在“ router.get('/',function(req,res){”)函数中获取该数据,然后像使用侧边栏var一样将结果作为变量传递到视图中,但这似乎并没有就是您要的。

To answer your specific question, what you want to do is - once the html gets to the browser, you'll want to make a call to those two endpoints and update the dom with javascript. 要回答您的特定问题,您想要做的是-一旦html到达浏览器,您将要调用这两个端点并使用javascript更新dom。 There are many ways to do that. 有很多方法可以做到这一点。 For simplicity sake, you could add a script tag under your div that, on page load ( Javascript that executes after page load ) makes an ajax request ( How to make an AJAX call without jQuery? ) to /ws/breaches?index=[a positive integer] and /ws/icon?site=[domain of a site] and updates the dom with the results ( https://www.w3schools.com/js/js_htmldom_html.asp ) 为简单起见,您可以在div下添加一个脚本标记,该标记在页面加载时(页面加载后执行的Javascript )向/ ws / breaches?index = [/ zh-CN /]发出ajax请求( 如何在不使用jQuery的情况下进行AJAX调用?正整数]和/ ws / icon?site = [站点的域名],并使用结果更新dom( https://www.w3schools.com/js/js_htmldom_html.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM