美文网首页
NodeJS 搭建简易 Web 服务器

NodeJS 搭建简易 Web 服务器

作者: 三分灰 | 来源:发表于2018-09-05 09:05 被阅读14次

静态 HTML 文件是可以直接在浏览器中打开的,不需要运行在服务器中,但是如果要在网页中测试一些数据请求的话,可能就需要将网页文件放在服务器环境中。

首先需要安装 NodeJS

参考这里教程,写的很详细
https://www.runoob.com/nodejs/nodejs-install-setup.html

安装好之后,开始上代码吧

server.js 放在项目文件夹下
server.js

var http = require('http');
var fs = require('fs');

var server= http.createServer(function(req,res){

    //得到客户端输入的url,输入 localhost:8888/index.html,则file='/index.html'
    //即得到访问的文件名
    var file = req.url; 

    //默认访问index.html
    if(file == '' || file == '/'){
        file = "/index.html";
    }

    //如果有参数的话,则去掉参数,提取出文件名,防止找不到文件
    //例如 localhost:8888/index.html?id=1,则file='index.html?id=1'
    //所以需进一步提取
    if(file.indexOf("?") != -1){
        file = file.split("?")[0];
    }
    console.log(file);
    //读取文件
    fs.readFile(__dirname + file , 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{
            var type = file.substr(file.lastIndexOf(".")+1,file.length)
            //如果请求的是css文件,Content-type需要单独设置为text/css
            if(type == 'css'){
                res.writeHead(200,{'Content-type':"text/"+type});
            }else{
                  res.writeHeader(200,{'content-type' : 'text/html;charset="utf-8"'});
            }
            res.write(data);//将index.html显示在客户端
            res.end();
        }
    });
}).listen(8888);

接下来只需要在打开命令行,进入该文件夹,输入以下命令运行该文件

node server.js
image.png
即可在 http://127.0.0.1:8888/ 访问网站。

相关文章

网友评论

      本文标题:NodeJS 搭建简易 Web 服务器

      本文链接:https://www.haomeiwen.com/subject/mucwwftx.html