我对外部帖子请求进行了测试。所以我这样开始我的应用程序:
var http = require('http');
var extreq = require('./app/external-request');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
var aaa = extreq.login();
response.end(JSON.stringify(aaa));
}).listen(1337, "127.0.0.1");
在“external-request.js”中,我有:
function login() {
request.post(url, { form: {
userid: 'myuserid',
password: '*****'
}
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
console.log(json); // Work
return json; // Not work
}
});
}
module.exports.login = login;
我的问题是,如何在这里获得“return json”“var aaa = extreq.login();”?
答案 0 :(得分:1)
这里的问题是request.post()
。这是一个异步方法,因此您的登录功能完成并在request.post()
调用完成之前返回。以下将显示实际情况:
function login() {
// obviously, you'll need to make sure you include whatever resources
// you need from 'external-request.js' before this
request.post(url, { form: { userid: 'myuserid', password: '*****' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
// this will log *after* the note in your main response body
console.log('this is the second thing your code will log to the console');
console.log(json); // Work
// this return doesn't actually go anywhere, it's just lost
return json; // Not work
}
});
return { whoops: 'this is what we really return' };
}
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
var aaa = extreq.login();
console.log('this is the first thing your code will log to the console');
response.end(JSON.stringify(aaa));
}).listen(1337, "127.0.0.1");
...运行它,你会看到你的代码没有像你期望的那样执行。
当人们提到使用回调时,他们所说的是你需要在request
完成在回调函数中发布外部请求时打包你想要发生的功能,然后它就可以了当它准备就绪时完成它的工作。如下所示:
var http = require('http');
var extreq = require('./app/external-request.js');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
extreq.login(function(aaa) {
response.end(JSON.stringify(aaa));
});
console.log('this is the first thing your code will log to the console');
}).listen(1337, "127.0.0.1");
...然后,您的登录功能:
function login(callback) {
request.post(url, { form: { userid: 'myuserid', password: '*****' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
// this will log *after* the note in your main response body
console.log('this is the second thing your code will log to the console');
console.log(json); // Work
// bonus points: pass in body directly, and skip stringify
callback(json);
}
});
return { whoops: 'this is what we really return' };
}