【问题标题】:Express render external Json to jade将外部 Json 快速渲染为玉
【发布时间】:2015-05-07 20:21:57
【问题描述】:

我有一个文件 (api.js),当我使用 node.js 在终端中调用它时,它会给出一个有效的 JSON 响应。我使用 request-promise 来执行 http 请求,并且该应用程序是 Express 样板。

现在我想将该响应添加到 Jade 文件并让 Jade 迭代 JSON 结果。

如何让 express 使用这个文件,然后将它传递给jade?​​p>

其次但不是必需的,我如何在 Jade 中获得一个按钮来使用相同的 api 进行 POST 请求,或者前端如何调用后端并在前端显示结果?

这是我的 api 文件 api.js:

var rp = require('request-promise');

var initGet = {
  uri: 'http://www.jsonapi.com/get',
  method: 'GET',
  headers: {"Content-Type": "application/json"}
};

var initPost = {
  uri: 'http://www.jsonapi.com/post',
  method: 'POST',
  headers: {"Content-Type": "application/json"},
  data: {},
  resolveWithFullResponse: true
};

var apiCall = function apiCall(options) {
// if request is GET
  if (options.method === 'GET') {
    rp(options)
      .then(function (res) {
        /// I assume this is where the response is sent to jade
      })
      .catch(console.error);
  }
// if request is POST
  else {
    rp(options)
      .then(function (res) {
        /// I assume this is where the response is sent to jade
      })
      .catch(console.error);
  }
};

var apiGet = function apiGet() {
  apiCall(initGet);
};

var apiPost = function apiPost(input) {
  initPost.data = input;
  apiCall(initPost);
};

// example of data in POST
apiPost({
  user: 2,
  event: 'World Cup 2018',
  name: 'Brazil'
});

module.exports = {
  apiGet: apiGet,
  apiPost: apiPost
};

在我的玉文件中:

extends layout
block content
  .title
    h1
      | App
  .ui
    each val in res
    .ui_box
      .ui_box__inner
        .event
          span val.event
        .name
          span val.name
      .drop
        p show drop down
        .arrow
    .ui_box.dropdown
      .submit-button
        p submit
        //submit POST

【问题讨论】:

    标签: javascript json node.js express pug


    【解决方案1】:

    我不能 100% 确定我是否完全理解您的问题,但我会试一试。

    您不会像您所说的那样“快速使用此文件然后将其传递给玉”,您只会在向服务器请求时呈现一个包含一些数据的玉文件。如果您愿意,该请求可以使用您的模块,但以这种方式表达它有助于理解其背后的概念。

    有关如何通过 express 使用模板引擎的信息,请阅读:http://expressjs.com/guide/using-template-engines.html

    您的端点将如下所示:

    var yourModule = require('./modules/yourModuleFile'); //note you don't need .js
    
    app.get('/', function (req, res) {
      yourModule.apiGet().then(function(result){
        res.render('yourTemplate', result);
      })
    })
    

    在写完那个例子之后,我想你可能对如何实际使用 Promise 有一个稍微不同的想法。你不会在你的模块内“做工作”,而是“返回用结果解决的承诺”。

    如果您需要关于最后一点的更多解释,请告诉我,我会扩展我的答案。

    【讨论】:

      【解决方案2】:

      经过反复试验,这是我的解决方案!!!

      我继续使用 request 对外部 jSON api 进行 http 调用。

      api.js:

      var request = require('request'); // require in request
      var initGet = {uri: 'http://linkToApi.com/get'};
      var initPost = {uri: 'http://http://linkToApi.com/post'};
      
      var apiCaller = function (url, cb) {
        //use request to make the external http call to the JSON api
        request({
          url: url,
          json: true
        }, function (error, response, body) {
      
          if (!error && response.statusCode === 200) {
            cb(body);// Send body/response to callback
          }
        })
      };
      // Call the api with a call back
      var apiGet = function(cb) {
        return apiCaller(initGet.uri, cb);
      };
      
      var apiPost = function(post, cb) {
        return apiCaller(initGet.uri + post, cb);
      };
      // Export the functions for external access
      module.exports = {
        apiGet: apiGet,
        apiPost: apiPost
      };
      

      现在是快速路线:

      var api = require('./api');
      var express = require('express');
      var router = express.Router();
      
      /* GET home page. */
      router.get('/', function(req, res, next) {
        //call the api apiGet and create callback function
        api.apiGet(function (data) {
          // render to the index.jade and pass the data from api call
          res.render('index', { result :data});
        });
      });
      

      最后在 index.jade 文件中:

      block content
        .ui
      //*** make sure the indentation is correct 'for' otherwise it doesn't parse!!
          for data in result //iterate through the results
            .ui_box
              .ui_box__inner
                .event
                  span #{data.event} // here pick out the jSON you require
                .name
                  span #{data.name}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-22
        • 2010-09-13
        • 2012-06-17
        • 2010-09-17
        • 2013-08-15
        • 2015-07-17
        相关资源
        最近更新 更多