最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Node.JS HTTP请求

IT培训 admin 6浏览 0评论

Node.JS HTTP请求

就像现在一样,Node HTTP请求的回调必须是请求中的匿名函数,如此...

http.request(params, function(res){
    let data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function() {
        console.log(data);
    });
}).end();

我想将回调分离到它自己声明的函数中,从相同或不同的文件中......就像这样......

function handleData(res) {
    let data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function(){
        console.log(data);
    });
}

https.request(params, handleData(res));

是否有可能做到这一点?任何地方都没有明确的答案。我觉得我是第一个尝试这个的人。在此先感谢您的时间!

回答如下:

它可以是这样的:

function handleResponse(res) {...yourcode...};
http.request(params, handleResponse).end();

或这个:

const handleResponse = function (res) {...yourcode...};
http.request(params, handleResponse).end();

要么

const handleResponse = res => {...yourcode...};
http.request(params, handleResponse).end();

要么

const handleResponse = res => {...yourcode...};
const request = http.request(params);
request.end();
request.on('response', handleResponse);

JavaScript和Node.js非常灵活。

Node.JS HTTP请求

就像现在一样,Node HTTP请求的回调必须是请求中的匿名函数,如此...

http.request(params, function(res){
    let data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function() {
        console.log(data);
    });
}).end();

我想将回调分离到它自己声明的函数中,从相同或不同的文件中......就像这样......

function handleData(res) {
    let data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function(){
        console.log(data);
    });
}

https.request(params, handleData(res));

是否有可能做到这一点?任何地方都没有明确的答案。我觉得我是第一个尝试这个的人。在此先感谢您的时间!

回答如下:

它可以是这样的:

function handleResponse(res) {...yourcode...};
http.request(params, handleResponse).end();

或这个:

const handleResponse = function (res) {...yourcode...};
http.request(params, handleResponse).end();

要么

const handleResponse = res => {...yourcode...};
http.request(params, handleResponse).end();

要么

const handleResponse = res => {...yourcode...};
const request = http.request(params);
request.end();
request.on('response', handleResponse);

JavaScript和Node.js非常灵活。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论