http.createServer()如何知道回调的参数?

这是图片

http.createServer((req,res)=>{});

createServer函数如何知道回调函数自动对传入消息对象具有“req”,对服务器响应对象具有“res”

有人可以给我看一个如何创建一个函数的例子,比如 createServer

回答

http.createServer()不知道您为回调参数声明了什么。无论您如何声明回调,http.createServer()在调用时都会向回调传递两个参数。第一个是http请求对象,第二个是http响应对象。如果您的回调想要正常工作并使用这些参数,则它必须创建两个与这些参数匹配的参数。您可以随意命名它们。该名称仅对您的回调是本地的。

因此,您可以执行以下任何操作:

http.createServer((request, response) => {
    response.end("hi");
});

http.createServer((req, res, goop) => {
    // goop will be undefined here since no third argument is passed to the callback
    res.end("hi");
});

http.createServer((a, b) => {
    b.end("hi");
});

http.createServer((...args) => {
    args[1].end("hi");
});

http.createServer(function() {
    arguments[1].end("hi");
});

有人可以向我展示如何创建像 createServer 这样的函数的示例吗

您可以创建一个接受回调函数的函数,然后使用一组参数调用该回调:

function readJSON(filename, callback) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            callback(err);
        } else {
            try {
                let json = JSON.parse(data);
                callback(null, json);
            } catch(e) {
                callback(e);
            }
        }
    });
}              
            

Here you create a function that takes a filename and a callback. It then reads that file, parses the JSON in it and calls the callback with null for the err and the parsed Javascript object for the 2nd parameter. If there's an error, then it just passes the error as the first argument.


以上是http.createServer()如何知道回调的参数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>