node初识

2022-06-06  本文已影响0人  wulle__

由官方提供 http 模块

1. 先引入 官方提供的 http 模块

let http=require('http');

2. 使用 http 模块中 createServer() 创建服务器

createServer() 中 参数是一个 回调函数
这个回调函数 有 两个参数
第一个参数 req  (请求)
第二个参数 res  (回应)

let server=http.createServer(function(req,res){
    // 配置相应信息
    // 发送 请求头
    // res对象中 writeHead()
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    // 发送响应数据
    res.write("<h1>你好,这是你人生中创建的第一个服务器</h1>");
    res.write("<h1>node1</h1>");
    res.write("<h1>node2</h1>");
    res.write("<h1>node3</h1>");
    res.end("<h1>响应结束!!!</h1>");// 结束响应
});

3. 设置端口号

let num=8888;
// 4. 监听浏览器地址栏  使用 server.listen();
// 有两个参数 第一个参数  监听的端口号  第二个参数  回调函数
server.listen(num,function(){
    console.log(`server is running at http://127.0.0.1:${num}`);
})
上一篇 下一篇

猜你喜欢

热点阅读