>>>>> NodeJS搭建本地服务器

  • 头部模块文件---mine.js
exports.types = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml"
};

搭建服务器文件---http.js

var PORT = 3000;//端口号

var http = require('http');//协议
var url=require('url');//读取路径模块
var fs=require('fs');//引入文件读取模块
var mine=require('./mine').types;//引入的上面头部文件模块并取到types对象
var path=require('path');//资源路径,符合web服务器路由约定即可

var server = http.createServer(function (request, response) {
    //request用来接收客服端数据,response用来向客服端发送服务器数据
    var pathname = url.parse(request.url).pathname;//解析路径名
    pathname=decodeURI(pathname);//路径解码--可能隐式编码
    var realPath = path.join("文件夹位置", pathname);//实际路径--绝对路径
    var ext = path.extname(realPath);//.html
    ext = ext ? ext.slice(1) : 'unknown';

    //console.log(realPath);
    //exists目标是否存在--true,false
    fs.exists(realPath, function (exists) {
        console.log(exists);//false;
        if (!exists) {
            response.writeHead(404, {//响应写入头部,状态码404--无法找到指定位置的资源
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {//状态码500--服务器遇到了意料不到的情况,不能完成客户的请求
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {//状态码200--OK  一切正常,对GET和POST请求的应答文档跟在后面
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");//服务器返回给我们的,并写入文件
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

在Node环境下运行http.js开启服务器,在浏览器中输入请求地址,这时为本地,加上端口号和文件即可访问相应文件
*注:文件类型需满足上方mine.js中类型

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,256评论 19 139
  • ## 前端开发的工具 ### 编辑器: 1. 轻量级的,依靠插件:sublime;atom(github);vs ...
    浪流儿阅读 3,286评论 0 2
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 前言 近期在准备搭建一个vue.js+node.js全栈开发的社区,之前由于没有云服务器搭建经验,这篇文章做一下相...
    技术宅小青年阅读 4,520评论 1 30
  • 跟老婆12年初认识,13年初恋爱,13年中订婚,14年底结婚,16年初我们的可爱儿子出生,四年多时间,近1400多...
    DennisFly阅读 153评论 3 0