个人头像

柠檬酸

4月前来过

控制台
欢迎来到我的博客!
默认封面

00:00/

播放列表

43行代码搭建一个node本地服务器

发布于2018-04-24 / 244次浏览

index.js

const PORT = 1234;//定义端口
const http = require('http');
const url=require('url');
const fs=require('fs');
const mine=require('./mine').types;
const path=require('path');
const startTime=new Date().getTime()
var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("react", pathname);    //这里设置自己的文件名称;
    var ext = path.extname(realPath);   //返回path路径文件扩展名
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(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, {
                        'Content-Type': 'text/plain'
                    });
                    response.end();
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
      
    });
});
server.listen(PORT);
const endTime=new Date().getTime();
console.log("Server runing at port: " + PORT + ".");
console.log(`花费 ${endTime-startTime} ms`)

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"
};

摘抄自脚本之家并稍作修改。

在目录下执行 node index.js 访问localhost:1234/react/xxx

可以随便跑ajax,再也不用担心跨域的问题了。

喜欢 1
TAGS:  
本站文章除注明转载/出处外,均为本站原创或翻译。若要转载但请务必注明出处,尊重他人劳动成果。 转载请注明出处链接 : 43行代码搭建一个node本地服务器

1 条评论

  1. 蝉時雨 说道: 来自 Google Chrome 65.0.3325.181 in Windows 10
    2018-04-26 9:11

    人生苦短,我用 Node :redface: