请求.JS和节点.js数据问题
Request.JS and Node.js Data problems
我是Node的新手,我正在开发一个使用Request.JS从私有API中提取数据的应用程序。 我需要在我的一个视图中显示数据。 目前,我的一个路由中需要并定义了请求,如下所示:
var models = require('../models');// Required for sequelize
var express = require('express');// Required for the Express framework
var router = express.Router();
var request = require('request');// For requesting API data
router.get('/', function (req, res) {
request( // Request from API
'http://PrivateAPI.com:8080/reports/22?type=0&key=privatekey',
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the return of the api call.
}
})
models.User.findAll({ // $$$-Define User DB call.
}).then(function(users) {
res.render('index', {
title: 'Project Insight',
users: users,
request: request
});
});
})
当它运行时,我可以在控制台中看到数据的输出,但我想知道让它在我的一个视图中显示的最佳方式。 另外,我甚至应该在我的路线中使用它吗? 迷路了,谢谢你的帮助。
首先,当前代码存在一些资源依赖问题,因为来自私有 API 的响应在渲染时可能不可用。我只是将数据库调用和后续操作移动到专用服务请求处理程序。对于实际答案:只需将更多数据传递给渲染操作即可:
router.get('/', function (req, res) {
request( // Request from API
'http://PrivateAPI.com:8080/reports/22?type=0&key=privatekey',
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
// response ok, continuing
models.User.findAll({ // $$$-Define User DB call.
}).then(function(users) {
res.render('index', {
title: 'Project Insight',
users: users,
request: request,
body: body // <--
});
} else {
// handle error
}
});
});
在您的视图/index.ejs 中,只需使用该变量。
<!DOCTYPE html>
<html>
...
Using <%= body %>, properties are also available if applicable ( <%= body.attr1 %>, <%= body.attr2 %>, ...)
...
</html>
相关文章:
- jQuery 和 Ajax 请求数据问题
- JSON Ajax 数据问题
- 请求.JS和节点.js数据问题
- EasyXDM传递数据问题
- Symfony2:Highchartsbundle数据问题
- Google Analtyics Embedded API - report.数据问题
- D3 JS - 未捕获的类型错误:无法读取未定义的属性“长度” - 似乎与数据问题有关
- 提前输入获取远程数据问题
- 异步加载数据问题 AngularJS 和 Firebase
- 提前输入.js远程发送之前发送帖子数据问题
- 在 HTML 结构中打印 JSON 数据问题
- Morris Donut图表没有数据问题
- 如何修复此本地数据问题?(Chrome扩展、Javascript、jQuery)
- 使用Spring MVC控制器在JQuery Datatable中呈现数据问题
- getJSON警报未返回任何内容-数据问题
- 渲染后挖空JS从视图模型中检索数据问题
- b4jjquery-websockets库发送数据问题
- Javascript数据表填充数据问题(没有返回错误)
- Angular数据问题——不知道如何排除
- 奇怪的jQuery数据()问题-帮助