zoukankan      html  css  js  c++  java
  • Node 版 http 服务器

    怎么样快速起一个静态服务?

    可以使用 http-server

    # 安装
    $ npm install http-server -g
    
    # 开启
    $ http-server -c-1
    Starting up http-server, serving ./
    Available on:
      http://127.0.0.1:8080
      http://192.168.8.196:8080
    Hit CTRL-C to stop the server
    

    但用代码怎么写一个 http 服务器?

    废话不多说直接上代码

    //a node web server.
    var http = require("http");
    var url = require("url");
    var fs = require("fs");
    
    var mimeTypes = {
      css: { "Content-Type": "text/css" },
      js: { "Content-Type": "text/javascript" },
      png: { "Content-Type": "image/png" },
      jpg: { "Content-Type": "image/jpeg" },
      svg: { "Content-Type": "text/xml" },
    };
    
    function start() {
      function onRequest(request, response) {
        var params = url.parse(request.url, true),
          pathname = params.pathname;
        //静态资源服务器
        //fs.readFile(filename,[options],callback);
        if (pathname === "/") {
          fs.readFile(__dirname + "/index.html", function (err, file) {
            if (err) throw err;
            response.write(file, "binary");
            response.end();
          });
        } else {
          fs.readFile(__dirname + pathname, "binary", function (err, file) {
            if (err && err.code === "ENOENT") {
              response.writeHead(404, { "Content-Type": "text/plain" });
              response.write(err + "
    ");
              response.end();
            } else if (err) {
              response.writeHead(500, { "Content-Type": "text/plain" });
              response.write(err + "
    ");
              response.end();
            } else {
              var type = pathname.slice(pathname.lastIndexOf(".") + 1);
              if (mimeTypes[type]) {
                response.writeHead(200, mimeTypes[type]);
              }
              
              //有callback字段则为jsonp请求。
              if (params.query && params.query.callback) {
                var str = params.query.callback + "(" + file + ")";
                response.end(str);
              } else {
                response.end(file); //普通的json
              }
            }
          });
        }
      }
      var port = process.argv[2] || 3000;
      http.createServer(onRequest).listen(port);
      console.log("Server has started at port " + port);
    }
    start();
    
    

    还缺功能:

    • MIME 支持更加完善
    • 路径是目录默认读 index.html
    • 缓存支持
    • 内容 Accept-Encoding 编码
  • 相关阅读:
    洛谷八连测R7 nzhtl1477-我回来了
    String中的equals方法原理分析
    Java线程
    Spring配置日志级别报红:Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'logging.level' to java.util.Map<java.lang.String
    # SpringMVC跨服务器上传文件出现的问题
    使用Maven创建Spring-web项目的基本流程
    Maven的下载与安装(环境变量的配置)
    eNSP的安装(附链接)
    数据库分页操作
    Sql语句占位符?的使用
  • 原文地址:https://www.cnblogs.com/everlose/p/12840121.html
Copyright © 2011-2022 走看看