Express render external Json 到 jade

Express render external Json to jade

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

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

如何让 express 使用这个文件,然后将其传递给 jade?

其次但不是必需的,我如何在 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
};

在我的 jade 文件中:

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

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

您不会像您所说的那样"get express to use this file and then pass it to jade",您只会根据对服务器的请求呈现一个包含一些数据的 jade 文件。如果您愿意,该请求可以使用您的模块,但以这种方式表达它有助于理解其背后的概念。

有关如何将模板引擎与 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);
  })
})

写完这个例子后,我认为您对如何实际使用 promises 的想法可能会略有不同。你不会 "do the work" 在你的模块中 "return the promise that resolves with the result"。

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

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

我继续使用 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}