http模块

介绍

Node中提供了http模块,其中封装了高效的http服务器和http客户端

http.Server是一个基于事件的http服务器,内部是由c++实现的,接口是由JavaScript封装

http.request是一个http客户端工具。 用户向服务器发送数据。

http.server事件

request:当客户端请求到来的时候,该时间被触发,提供两个参数request 和 response,分别是http.ServerRequest 
和 http.ServerResponse 表示请求和响应的信息

connection:当TCP建立链接的时候,该时间被处罚,提供了一个参数 socket ,为net.socket的实例(底层协议对象)

close:当服务器关闭的时候会被触发

案例

const http = require("http");
const server = http.createServer();
server.on("request", (req, res) => {
    res.setHeader("Content-Type", "text/html;charset=utf-8");
    let content = "";
    if (req.url == "/" || req.url == "/index.html") {
        content = "<h1>首页内容</h1>";
    } else if (req.url == "/detail.html") {
        content = "<h1>详情页内容</h1>";
    } else {
        content = "<h1>你访问的页面不存在</h1>";
    }
    res.end(content);
});
server.listen(8080, () => {
    console.log("server is listen:127.0.0.1或者localhost");
});
powered by GitbookEdit Time: 2024-06-06 18:25:41