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是同级的

  • 相关阅读:
    BS文件夹上传操作(一)
    ext.net 开发学习— 2012 上半年 总结
    C#泛型泛型方法
    C#泛型泛型类
    文件读取,保存操作
    itools下载链接被360警告:虚假招聘网站
    读书推荐:《wordpresss博客建站与经营》
    Net CF简单介绍
    木杉大话微软手机系统
    wp7和wp8的区别
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/12187029.html
Copyright © 2011-2022 走看看