// server.js
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const httpPort = 8889;
function onRequest(request, response) {
console.log('———— start ——————————');
const myURL = url.parse(request.url);
// 获取请求的决定路径。(dirname:目录名称)
let pathname = path.join(__dirname, myURL.pathname);
console.log(`原始请求路径: ${pathname}`);
// 设置跨域白名单
response.setHeader('Access-Control-Allow-Origin', '*');
if (myURL.pathname === '/') {
// 如果请求路径最后面为'/'或者连'/'都没有,就要加上默认值'/index.html',使用path模块
pathname = path.join('index.html');
} else if (!/[.]\D+$/gi.test(path.basename(pathname))) {
// 如果 最后面为 '/index','/about' 之类,则在后面加上'.html'后缀。
pathname = path.join('index.html');
}
console.log(`处理后的路径: ${pathname}`);
fs.stat(pathname, (error, stats) => {
if (!error && stats.isFile()) {
switch (path.extname(pathname)) {
case '.html':
response.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8;',
});
break;
case '.js':
response.writeHead(200, {
'Content-Type': 'text/javascript',
});
break;
case '.css':
response.writeHead(200, { 'Content-Type': 'text/css' });
break;
case '.json':
response.writeHead(200, { 'Content-Type': 'text/json' });
break;
case '.gif':
response.writeHead(200, { 'Content-Type': 'image/gif' });
break;
case '.jpg':
response.writeHead(200, { 'Content-Type': 'image/jpeg' });
break;
case '.png':
response.writeHead(200, { 'Content-Type': 'image/png' });
break;
default:
response.writeHead(200, {
'Content-Type': 'application/octet-stream',
});
}
fs.readFile(pathname, (err, data) => {
response.end(data);
});
} else {
response.writeHead(200, {
'Content-Type': 'text-plain;charset="utf-8";',
});
response.end('<p>404 找到的你请求的资源!</p>');
}
});
}
http.createServer(onRequest).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort);
});
// const http = require('http');
// const fs = require('fs');
// const httpPort = 8899;
// http.createServer((req, res) => {
// if (
// req.url.startsWith('/css') ||
// req.url.startsWith('/js') ||
// req.url.startsWith('/img') ||
// req.url.startsWith('/ckeditor')
// ) {
// fs.readFile('.' + req.url, (err, data) => {
// res.end(data);
// return;
// });
// }
// fs.readFile('index.html', 'utf-8', (err, content) => {
// if (err) {
// console.log('We cannot open "index.htm" file.');
// }
// res.writeHead(200, {
// 'Content-Type': 'text/html; charset=utf-8',
// });
// res.end(content);
// });
// }).listen(httpPort, () => {
// console.log('Server listening on: http://localhost:%s', httpPort);
// });
启动 node server.js