【问题标题】:How do I store a value from an API call with node.js Express and Mikeal's npm-request?如何使用 node.js Express 和 Mikeal 的 npm-request 存储来自 API 调用的值?
【发布时间】:2018-02-03 04:23:40
【问题描述】:

我刚刚开始尝试使用 node Express,并希望在我的 HTML 中显示来自 API(我用 Ruby/Sinatra 制作)的一些文本。我可以console.log() 我想要的文本,但我在将它保存到一个变量以在我的ejs 文件中调用时遇到问题。如何从调用 API 的 JSON 中获取值并将其放置在我的页面上? 这是我的代码。

这是我的主要 Js 文件。


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

var routes = require('./routes');
app.set('view engine', 'ejs');

app.get('/', routes.index);
app.get('/about', routes.about);

var server = app.listen(3000, function() {
  console.log('look at port 3000')
})

这是我的索引路线


var request = require('request');
var resq = request("http://ancient-falls-7604.herokuapp.com/users/1/posts", function(error, response, body) {
  console.log (JSON.parse(body)["user_posts"][1]["post"]["body"])
}) 
// this thing I just console.logged is what I want saved to a var

exports.index = function(req, res){
  res.render('main', {
    title: 'Some Random Title',
    sinatra: "JSON CALL WILL EVENTUALLY GO"
  });
};

最后这是我的 ejs 文件


<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1> <%= title %></h1>
<p><%= sinatra %></p>

</body>
</html>

【问题讨论】:

    标签: javascript node.js api express


    【解决方案1】:

    只需在 index 方法中提出您的请求,将其保存到您的变量并调用 render:

    exports.index = function(req, res){
      request("http://ancient-falls-7604.herokuapp.com/users/1/posts", function(error, response, body) {
        var json = JSON.parse(body);
        res.render('main', {
          title: json.user_posts[0].post.title,
          sinatra: json.user_posts[0].post.body
        });
      });
    };
    

    要实现这一点,请确保您的视图文件的名称是 main.ejs,因为您在渲染方法中调用了 main

    【讨论】:

      【解决方案2】:

      对于ejs,你需要使用

      res.render('fileName.ejs', {data: data, moreData: moreData, ...})
      

      然后你就可以在指定的文件中访问它了:

      <%= data %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多