[Node.js] 模块化 -- http服务器模块

使用http模块创建一个服务器

在这里插入图片描述

  • 1.导入http模块
  • 2.创建一个服务器
  • 3.设置返回给用户看的内容
  • 4.开启服务器

在这里插入图片描述

//使用内置模块http来创建一个服务器

//1.导入http模块
const http = require( 'http' );


//2.创建一个服务器
//这个方法有一个返回值,返回值就代表这个服务器
const  server = http.createServer((request,response)=>{
    //3.设置返回给用户看的内容
    // response .end('hellow world!')
    
    //如果想要返回去的中文不乱码,那就要设置响应头.
    response. setHeader( 'Content-Type', ' text/html;charset=utf-8 ');
    response.end('初次见面,请多关照!')
});


//4.开启服务器
//端口
server.listen(8087,()=>{
    console.log('服务器开启了:8087');
})


 
 

web服务器读取网页返回给用户

在这里插入图片描述

  • 1.导入http, fs ,path模块
  • 2.创建服务器
  • 3.读文件返回
    • 3.1拼接要读取的文件的路径
    • 3.2读取这个文件的内容
  • 4.开启服务器

在这里插入图片描述

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html{
            margin: 0px;
            padding: 0px;
            height: 100%;
            overflow: hidden;
        }
        body{
            background: linear-gradient(to bottom ,red,green,blue);
        }
    </style>
</head>
<body>
<div>这是一个寂寞的天</div>
<p>下着有些伤心的雨</p>
</body>
</html>

js部分

//1.导入http, fs ,path模块
const fs = require('fs' );
const http = require( 'http' );
const path = require( 'path' );

//2.创建服务器
const  server = http.createServer((request,response)=>{
    //3.读文件返回
    //3.1拼接要读取的文件的路径
    const fullPath = path. join(__dirname ,'web', 'index.html ')
    //3.2读取这个文件的内容
    fs . readFile(fullPath, 'utf-8' , (err, data)=>{
        if (err == null){
            //3.3 返回给用户
            response.end(data);
        } else {
            response.end('404')
        }
    })
})

//4.开启服务器
//端口
server.listen(4399,()=>{
    console.log('服务器开启了:4399');
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值