簡體   English   中英

Express將外部Json渲染為玉器

[英]Express render external Json to jade

我有一個文件(api.js),當我使用node.js在終端中調用它時,它會提供有效的JSON響應。 我已經使用request-promise來執行http請求,並且該應用程序是Express的樣板。

現在,我想將該響應添加到Jade文件中,並讓Jade迭代JSON結果。

我如何獲得快遞使用該文件並將其傳遞給玉的信息?

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

這是經過反復試驗的我的解決方案!!!

我繼續並使用了對外部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}

我不確定我是否完全理解您的問題,但我不會100%確定。

就像您所說的那樣,您不會“得到明確的使用權,然后將其傳遞給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);
  })
})

在寫完該示例之后,我認為您可能對如何實際使用Promise略有不同的想法。 您無需在模塊內部“完成工作”,而是“返回以結果解決的承諾”。

如果您需要在這最后一點上做更多說明,請告訴我,我將擴大答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM