我正在努力解决使用 Node 请求将模型文件中的一些数据传回 Controller 的最后一步。
我已成功从模型文件设置回调,该文件使用请求从外部源加载 JSON。
我的 Controller 可以访问它,但我认为在最后一步中我仍然需要某种嵌套的第二个回调,因为我希望变量 pageJSON 包含 JSON 对象,但不太清楚如何实现。
我想我在这方面遇到了一些困难,如果对这个问题有一些新的看法,我们将不胜感激!感觉我现在错过了一些非常简单的东西(我希望!)
我的模型文件:
module.exports = function (config, callback) {
const request = require('request');
const options = {
'url' : config.urls.page,
'json' : true,
'auth': {
'user': config.auth.username,
'pass': config.auth.password
}
};
request(options, (error, response, body) => {
if (error) {
console.log(error);
}
callback(body);
});
}
我的 Controller 文件:
const express = require('express');
const router = express.Router();
const app = express();
const config = require('../config');
const page = require('../models/page');
let pageJSON = page(config, (json) => {
console.log(json); // This shows the JSON structure in console
return json;
});
console.log(pageJSON); // Undefined
// Manipulate JSON and pass request view accordingly using Express
最佳答案
您必须在 Controller 回调中处理 json 操作(或从中调用另一个回调):
let pageJSON = page(config, (json) => {
console.log(json); // This shows the JSON structure in console
processJSON(json);
});
pageJSON
是未定义
,因为您的模型没有返回任何内容。
关于javascript - 在 MVC 结构中使用 Express + Request Node 模块的异步嵌套回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709146/