zoukankan      html  css  js  c++  java
  • 【node开发】node简易服务器一分钟搞定

    1、新建一个server.js文件

    var http = require('http'); //用来启服务
    var fs = require('fs'); //用来读取文件
    var root = __dirname //你本地放index.html页面的文件路径
    console.log(root)
    //开启服务
    var server = http.createServer(function(req, res) {
        var url = req.url;
        console.log(url)
        var file = root + url;
        redfile(file, req, res)
    }).listen(8088); //端口号
    function redfile(url, req, res) {
        let contentType = 'text/html;charset="utf-8"'
        if (/.html$/.test(url)) {
            contentType = 'text/html;charset="utf-8"'
        } else if (/.css$/.test(url)) {
            contentType = 'text/css; charset=utf-8'
        } else if (/.js$/.test(url)) {
            contentType = 'application/javascript; charset=utf-8'
        } else if (/.jpg$/.test(url)) {
            contentType = 'image/jpg'
        } else if (/.png$/.test(url)) {
            contentType = 'image/png'
        } else if (/.ico$/.test(url)) {
            contentType = 'image/png'
        }
        fs.readFile(url, function(err, data) {
            if (err) {
                res.writeHeader(404, {
                    'content-type': 'text/html;charset="utf-8"'
                });
                res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
                res.end();
            } else {
                res.writeHeader(200, {
                    'content-type': contentType
                });
                res.write(data); //将index.html显示在客户端
                res.end();
            }
        })
    }
    console.log('8088端口服务器开启成功');

    2、再终端运行该文件  

    node server.js

    3、浏览器打开index.html页面

    http://localhost:8088/index.html

    注意自己目录,这里我server.js 和 index.html是同级的

  • 相关阅读:
    环境变量
    多重继承
    参数检查(@property)
    限制属性绑定(__slots__)
    实例属性和类属性
    2017-11-28 中文编程语言之Z语言初尝试: ZLOGO 4
    2017-10-23 在各种编程语言中使用中文命名
    2017-11-27 汉化了十数个编译器的前辈的心得体会
    五行
    阴阳
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/12187029.html
Copyright © 2011-2022 走看看