node.js学习5--------------------- 返回html内容给浏览器

/**
 * http服务器的搭建,相当于php中的Apache或者java中的tomcat服务器
 */
// 导包
const http=require("http");
const fs=require("fs");
//创建服务器
/**
 * 参数是一个回调函数,回调函数2个参数,1个是请求参数,一个是返回参数
 */
let server=http.createServer((req,res)=>{
    console.log(req.url);//打印请求的url
    //根据不同的请求路径来响应内容:/响应首页index,/login响应登录页
    if("/"==req.url){
        //一般如果返回的是文本,不需要设置请求头,浏览器可以解析
        fs.readFile("/index.html","utf-8",(err,data)=>{
            if(err){
                throw err;
            }else{
                res.end(data);
            }
        });
    }else if("/login"==req.url){
        
        fs.readFile("/login.html","utf-8",(err,data)=>{
            if(err){
                throw err;
            }else{
                res.end(data);
            }
        });
    }else{
        res.end("404 NOT Found");
    }

});
//监听
/**
 * 第一个参数是端口,第二个参数是ip地址,默认不写就是本地地址,第三个是回调函数
 */
server.listen(8980,"127.0.0.1",()=>{
    console.log("服务器启动成功");
});
原文地址:https://www.cnblogs.com/yangxiaohui227/p/10666012.html