nodejs 一个简单的web服务器,用于前端自己快速测试部署
1.资源路径不能有中文,否则访问失败。后面再慢慢解决。
(node环境)启动命令:node node-web-server.js
var http=require('http');
var fs = require('fs');
var url = require('url');
//创建服务器
http.createServer(function(request,response) {
//后端设置允许跨域
response. setHeader("Access-Control-Allow-Origin","*");
//解析请求,包括文件名
var parseUrl = url.parse(decodeURI(request.url));
// var parseUrl = url.parse(request.url);
var pathname= parseUrl.pathname;
//输出请求的文件名
console.log("Request for "+ pathname + " received.");
//获取后缀,判断是js还是css文件,如果目录结构不同,此处需要修改
var firstDir = pathname && pathname.split('/')[1];
// var firstDir = pathname && pathname.split('/')[1];
var suffix = pathname && pathname.split('.').slice(-1).toString();
var ContentType = {'Content-Type': 'text/html;charset=utf-8'};
// js - application/x-javascript
if (suffix && suffix === 'css') {
ContentType = {'Content-Type': 'text/css;charset=utf-8'};
} else if (suffix && suffix === 'js') {
ContentType = {'Content-Type': 'application/x-javascript;charset=utf-8'}
} else if (suffix && suffix === 'png') {
ContentType = {'Content-Type': 'image/png'}
}
// 超文本标记语言文本 .html text/html
// xml文档 .xml text/xml
// XHTML文档 .xhtml application/xhtml+xml
// 普通文本 .txt text/plain
// RTF文本 .rtf application/rtf
// PDF文档 .pdf application/pdf
// Microsoft Word文件 .word application/msword
// PNG图像 .png image/png
// GIF图形 .gif image/gif
// JPEG图形 .jpeg,.jpg image/jpeg
// au声音文件 .au audio/basic
// MIDI音乐文件 mid,.midi audio/midi,audio/x-midi
// RealAudio音乐文件 .ra, .ram audio/x-pn-realaudio
// MPEG文件 .mpg,.mpeg video/mpeg
// AVI文件 .avi video/x-msvideo
// GZIP文件 .gz application/x-gzip
// TAR文件 .tar application/x-tar
// 任意的二进制数据 application/octet-stream
console.log(suffix, ContentType);
//从文件系统中去请求的文件内容
fs.readFile(pathname.substr(1),function(err, data) {
if(err) {
console.log(err);
//HTTP 状态码 404 : NOT FOUND
//Content Type:text/plain
response.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
}
else {
//HTTP 状态码 200 : OK
//Content Type:text/plain
response.writeHead(200, ContentType);
//写会回相应内容
if (['png'].includes(suffix)) {
response.write(data, "binary");
} else {
response.write(data.toString());
}
}
//发送响应数据
response.end();
});
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');