【发布时间】: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