简体   繁体   English

api在带有节点js的header.ejs文件上获取请求

[英]api get request on a header.ejs file with node js

i'd like to display data from an endpoint on a header.ejs file which will be shown on all the routed files (eg "/", "/news" "/dogs") 我想在header.ejs文件上显示来自端点的数据,该文件将显示在所有路由文件中(例如“ /”,“ / news”,“ / dogs”)

here's my app.js code: 这是我的app.js代码:

// GET API REQUEST
var url = 'https://url.tld/api/';
request(url, function (error, response, body) {
    if(!error && response.statusCode == 200) {
        var parsedData = JSON.parse(body);
        return parsedData;
    }
});

app.get("/", function(req, res) {
    res.render("index.ejs", {parsedData: parsedData});   
    });

the code from header.ejs: header.ejs中的代码:

<li>Active players: <span><%= parsedData["players"] %></span></li>

I get a parsedData is undefined error and I dont know how to get it done in any way. 我收到一个parsedData是未定义的错误,我不知道如何以任何方式完成它。 I want to show the active players and a server status in the navbar. 我想在导航栏中显示活动的播放器和服务器状态。 What's a common practice to achive this? 实现此目的的常用方法是什么?

Thanks in advance! 提前致谢!

Probably you should solve this problem using middleware. 可能您应该使用中间件解决此问题。

From the express docs : 快递文档

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. 中间件功能是可以访问请求对象(req),响应对象(res)和应用程序的请求-响应周期中的下一个中间件功能的功能。 The next middleware function is commonly denoted by a variable named next. 下一个中间件功能通常由名为next的变量表示。

Middleware functions can perform the following tasks: 中间件功能可以执行以下任务:

  • Execute any code. 执行任何代码。
  • Make changes to the request and the response objects. 更改请求和响应对象。
  • End the request-response cycle. 结束请求-响应周期。
  • Call the next middleware function in the stack. 调用堆栈中的下一个中间件函数。

Middleware always take the request, the response, and the function next as arguments. 中间件始终以请求,响应和功能next作为参数。 You do whatever you need to do, and then call next to move onto the next thing on the list. 您可以做任何您需要做的事,然后调用next移至列表中的下一件事。

So, for example, if you wanted to write a simple middleware that would log the time every time the app received a request, you'd say something like: 因此,例如,如果您想编写一个简单的中间件,该中间件将记录应用程序每次收到请求的时间,那么您会说:

app.use(function(req, res, next) {
  console.log(Date.now())
  next()
})

So in your case, maybe you'd say: 因此,就您而言,也许您会说:

app.use(function(req, res, next) {
  // stuff
  request(url, function(err, response, body) {
    //stuff
    res.locals.parsedData = parsedData
  })
})

And then in your res.render , you'd say 然后在您的res.render ,您会说

res.render('index.ejs', {parsedData: res.locals.parsedData})

Again from the express docs : 再次从快递文档

[res.locals is] An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). [res.locals是]一个对象,它包含范围为请求的响应局部变量,因此仅可用于在该请求/响应周期(如果有)中呈现的视图。 Otherwise, this property is identical to app.locals. 否则,此属性与app.locals相同。

If you know you'll only need to make this request once, attach the parsed data to app.locals instead, and then in the middleware, add a check to see if app.locals.parsedData exists before you run the request. 如果您知道只需要发出一次请求,则将解析的数据附加到app.locals ,然后在中间件中添加检查以查看app.locals.parsedData存在,然后再运行请求。

Hope this helps! 希望这可以帮助!

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

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