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

  • 相关阅读:
    vue项目搭建过程2 -- 使用 vue cli 4.0 搭建 vue 项目
    vue项目搭建过程1 -- 环境搭建
    升级node.js版本
    git的初步了解
    期末总结
    四则运算的封装
    用户故事
    0~10的随机整数运算
    创业近一年在博客园总结一下,希望给来者一点借鉴
    PV与并发之间换算的算法换算公式
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/12187029.html
Copyright © 2020-2023  润新知