zoukankan      html  css  js  c++  java
  • 小服务器

    server.js

    const http = require("http");
    const url = require("url");
    const globalConf = require("./config.js")
    const fs = require("fs");


    http.createServer(function(request, response){
    const pathName = url.parse(request.url).pathname;
    const params = url.parse(request.url, true).query;
    const isStatic = isStaticFile(pathName);
    if(isStatic){
    try{
    const fileData = fs.readFileSync(globalConf.page_path + pathName);
    response.writeHead(200);
    response.write(fileData);
    response.end();
    }catch(e){
    response.writeHead(404);
    response.write("<html><body><h1>404 NOT FOUND</h1></body></html>");
    response.end();
    }
    }else{
    // response.end();
    const fileData = fs.readFileSync(globalConf.page_path + pathName);
    response.writeHead(200);
    response.write(fileData);
    console.log(globalConf.page_path + pathName);
    }
    }).listen(globalConf.port)

    function isStaticFile(pathName){
    if(pathName && globalConf.static_file_type){
    for (let i = 0; i < globalConf.static_file_type.length; i++) {
    const file_type = globalConf.static_file_type[i];
    if (pathName.indexOf(file_type) == pathName.length - file_type.length){
    return true
    }
    }
    return false
    }
    }

    server.conf
    port=8080
    page_path=page
    static_file_type=.html|.css|.png|.ico|.gif|.jpg

    config.js
    const fs = require("fs");
    const conf = fs.readFileSync("./server.conf")
    const globalConf = {};

    const conList = conf.toString().split(" ");
    for (let i = 0; i < conList.length; i++) {
    const conformist = conList[i].split("=");
    if (conformist && conformist.length == 2){
    globalConf[conformist[0]] = conformist[1];
    }
    }
    if(globalConf.static_file_type){
    globalConf.static_file_type = globalConf.static_file_type.split("|");
    }else{
    throw new Error("配置文件异常,缺少:static_file_type")
    }
    module.exports = globalConf;

    login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="login.js"></script>
    </head>
    <body>
    <img src="myLove.jpg">
    </body>
    </html>
    login.js
    window.onload = function(){
    console.log("你好login.js")
    const ajax = new XMLHttpRequest();
    ajax.open("GET","/getData",true);
    ajax.send(null);
    ajax.onreadystatechange = function(){
    if(ajax.onreadyState == 4 && ajax.status == 200){
    console.log(ajax.responseText);
    console.log(typeof ajax.responseText);
    }
    }
    }
     
  • 相关阅读:
    贪心-poj-3040-Allowance
    [置顶] .net技术类面试、笔试题汇总3
    数据对接—kettle使用之二
    做好先期工作,才能有效沟通
    cc++复习基础要点08--c++单例模式
    android 限制adb的访问目录
    我奋斗18年,和你或者咖啡没有任何关系
    (3)选择元素——(15)总结(Summary)
    (3)选择元素——(16)延伸阅读(Further reading)
    网络协议复习
  • 原文地址:https://www.cnblogs.com/qydknowledge/p/13466880.html
Copyright © 2011-2022 走看看