十七、创建一个 WEB 服务器

1、Node.js 创建的第一个应用

var http=require("http")
http.createServer(function (req,res) {
    res.writeHead(200,{"Content-Type":"text/html;charset='utf8'"})
    res.write("<head><meta charset='UTF-8'></head>")
    res.write("hello,Node.js!!!")
    res.end()
}).listen(8081)

2、WEB 服务器介绍

Web 服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,可以向浏览
器等 Web 客户端提供文档,也可以放置网站文件,让全世界浏览;可以放置数据文件,让
全世界下载。目前最主流的三个 Web 服务器是 Apache Nginx IIS。

3、Nodejs 创建一个 WEB 服务器。

返回html页面示例:

js代码:

//引入http模块:
var http = require("http");
//引入fs模块:
var fs = require("fs");
http.createServer(function (req, res) {
    var urlStr = req.url;//获取浏览器输入的地址
    console.log(urlStr);
    if (urlStr == '/') {//設置默认加载的頁面
        urlStr == '/index.html';
    }
    if (urlStr != '/favicon.ico') { //过滤无效请求:/favicon.ico
        //通过文件操作模块读取静态页面内容
        fs.readFile("html" + urlStr, function (err, data) {
            if (err) {//没有这个文件
                console.log("404");
                return;
            } else {
                res.writeHead(200, {"Content-Type": "text/html;charset='utf8'"})
                res.write(data)
                res.end()
            }
        })
    }
}).listen(8081)

html文件代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    div{
        width: 100px;
        height: 200px;
        background-color: red;
        margin: 0 auto;
    }
</style>
<body>
<div></div>
</body>
</html>

效果:

猜你喜欢

转载自www.cnblogs.com/luzhanshi/p/10763776.html