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);
}
}
});
}
在这里您创建一个带有文件名和回调的函数。然后它读取该文件,解析其中的 JSON,并使用
null
来调用回调函数以获取错误,并使用解析后的 Javascript 对象作为第二个参数。如果出现错误,那么它只是将错误作为第一个参数传递。
HTTP 是一个包含 1 个名为 createServer 的函数的类,您可以在此处找到有关 HTTP 对象的一些详细信息https://nodejs.org/api/http.html,当发生请求之类的情况时,服务器会返回您的带一些参数的回调函数。
希望通过1个例子会更容易理解:
您有以下课程:
class User {
userInfo = {
name: "Jhon",
surname: "Doe"
}
getFullName = (callback) => {
return callback(this.userInfo.name, this.userInfo.surname)
}
}
这个类有 2 个定义的属性,userInfo 包含“用户”的名字和姓氏,以及 1 个函数 getFullName,该函数需要另一个函数作为输入,每当我们调用它时,我们都会收到 2 个参数作为输出:
const UserInfo = new User()
UserInfo.getFullName((name,surname) => console.log(`Hello ${name} ${surname}`))
希望这能回答您的问题,如果您还有任何其他问题或我完全误解了您的问题,请随时告诉我!