javascript Node JS 上的 HTTP 请求回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33851938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:58:34  来源:igfitidea点击:

HTTP request callback on Node JS

javascriptjsonnode.jshttp

提问by mattts

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.

嗨,我正在尝试使用回调方法通过 http 获得响应。但是我收到一条错误消息,说回调不是函数。

 module.exports.ipLookup = function (res, callback) {
    var http = require('http');
    var str = '';
    var options = {
        host: 'ip-api.com',
        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.com. If anyone can help me on this it would be greatly appreciated.

通过 ip-api.com id 返回 json api 响应应该做什么。如果有人可以帮助我,将不胜感激。

回答by simon-p-r

In 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.com',
        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();

}