admin管理员组文章数量:1401307
Hi I am trying to get a response via a http using the callback method. But I get an error saying callback is not a function.
module.exports.ipLookup = function (res, callback) {
var http = require('http');
var str = '';
var options = {
host: 'ip-api',
port: 80,
path: '/json/',
method: 'POST'
};
var str= "";
var req = http.request(options, function (res) {
res.on('data', function (body) {
str += body;
});
res.on('end', function () {
callback(str);
});
});
req.end();
return str;
}
What is should to id return the json api response via ip-api. If anyone can help me on this it would be greatly appreciated.
Hi I am trying to get a response via a http using the callback method. But I get an error saying callback is not a function.
module.exports.ipLookup = function (res, callback) {
var http = require('http');
var str = '';
var options = {
host: 'ip-api.',
port: 80,
path: '/json/',
method: 'POST'
};
var str= "";
var req = http.request(options, function (res) {
res.on('data', function (body) {
str += body;
});
res.on('end', function () {
callback(str);
});
});
req.end();
return str;
}
What is should to id return the json api response via ip-api.. If anyone can help me on this it would be greatly appreciated.
Share Improve this question asked Nov 22, 2015 at 5:29 matttsmattts 3522 gold badges8 silver badges21 bronze badges 2-
1
How are you using/invoking
ipLookup()
? The value ofcallback
will be determined there. – Jonathan Lonowski Commented Nov 22, 2015 at 5:55 - @JonathanLonowski, thanks for the reply. I am requiring the js file onto another file. e.g. var lookup = require('ip'); using lookup.ip(); – mattts Commented Nov 22, 2015 at 8:35
1 Answer
Reset to default 4In the other file you are loading the function from you need to ensure the callback parameter is used. See snippet below
var Lookup = require('./ip');
Lookup.ipLookup(function (response) {
console.log(response) // check if response is valid
})
You need to change the exported function to only accept one parameter as the first parameter is not used inside function body like so.
module.exports.ipLookup = function (callback) {
var http = require('http');
var str = '';
var options = {
host: 'ip-api.',
port: 80,
path: '/json/',
method: 'POST'
};
var req = http.request(options, function (res) {
res.on('data', function (body) {
str += body;
});
res.on('end', function () {
return callback(str);
});
});
req.end();
}
本文标签: javascriptHTTP request callback on Node JSStack Overflow
版权声明:本文标题:javascript - HTTP request callback on Node JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744297220a2599401.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论