小服务器

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);
}
}
}
 
原文地址:https://www.cnblogs.com/qydknowledge/p/13466880.html