準備:写真の
ようなマテリアルポータルを準備します:
この記事に必要なマテリアルと完全なコード
1.詳細な手順
httpサービスを作成する
// app.js
const http = require('http'); // 加载http服务模块
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'});
res.end(); // 结束响应
}).listen(3000); // 设置端口号
console.log('Server running at http://127.0.0.1:3000/');
URLを取得する
// 我们要获取类似这样的url,来展示对应的内容
http://localhost:3000/index.html
let pathName = req.url;
console.log(pathName); // /index.html /favicon.ico
2つのリクエストが送信されたため、リクエスト/favicon.icoを除外する必要があることがわかりました。同時に、空のアドレスを処理する必要があります。コードは次のとおりです。
// app.js
const http = require('http'); // 加载http服务模块
http.createServer(function (req, res) {
let pathName = req.url;
pathName = pathName == '/' ? '/index.html' : pathName;
if(pathName != '/favicon.ico'){
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'});
res.end();
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
ファイルを読む
最初にfsモジュールをロードします。要求されたページが見つからない場合は、404ページをロードします。
// app.js
const http = require('http'); // 加载http服务模块
const fs = require('fs');
http.createServer(function (req, res) {
// http://127.0.0.1:3000/login.html
// 1. 获取地址
let pathName = req.url;
pathName = pathName == '/' ? '/index.html' : pathName;
// 2. 通过fs模块读取文件
if(pathName != '/favicon.ico'){
fs.readFile(`./static${
pathName}`,(err,data) => {
if(err){
fs.readFile('./static/404.html',(err,data404)=>{
if(err){
console.log('404')
}else{
res.writeHead(404, {
'Content-Type': 'text/html;charset=utf-8'});
res.end(data404);
}
})
}else{
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'});
res.end(data);
}
})
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
この時点で、次のような効果をすでに確認できます。リクエストヘッダーを設定します
要求されたすべてのファイルヘッダーを「Content-Type」に設定したため:「text / html; charset = utf-8」;
これは明らかに間違ったアプローチです。例:cssファイルは「text / css」に設定する必要があり、jsファイルは「text / javascript」に設定する必要があります。
まず、フォルダーを作成し、モジュールという名前を付けて、
次のようにフォルダー内にjsファイルcommon.jsコードを作成します。
// common.js
const fs = require('fs');
exports.getFileMime = (extName) => {
// readFileSync 为 readFile 的同步方法
let data = fs.readFileSync('./data/mime.json'); // 注意:因为该方法在 app.js 引用,所以相对位置应以app.js为基点
let mimeObj = JSON.parse(data.toString());
return mimeObj[extName]
}
対応するリクエストのファイルサフィックスに従って対応するファイル形式を設定する必要があるため、パスモジュールを導入する必要があります。次に、path.extname()メソッドを使用して、対応するサフィックス名を取得します。
// app.js
const http = require('http'); // 加载http服务模块
const fs = require('fs');
const path = require('path');
const common = require('./moudle/common');
http.createServer(function (req, res) {
// http://127.0.0.1:3000/login.html
// 1. 获取地址
let pathName = req.url;
pathName = pathName == '/' ? '/index.html' : pathName;
// 获取后缀名 path.extname();
let extname = path.extname(pathName)
console.log(pathName)
// 2. 通过fs模块读取文件
if(pathName != '/favicon.ico'){
fs.readFile(`./static${
pathName}`,(err,data) => {
if(err){
fs.readFile('./static/404.html',(err,data404)=>{
if(err){
console.log('404')
}else{
res.writeHead(404, {
'Content-Type': 'text/html;charset="utf-8"'});
res.end(data404);
}
})
}else{
let mime = common.getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
res.writeHead(200, {
'Content-Type': `${
mime};charset="utf-8"`});
res.end(data);
}
})
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
結果は図のようになります。
ただし、対応する画像は読み込まれません。これは次の理由によるものです。リクエストアドレスにはパラメータがあり、認識できないため、これら2つのファイルは読み込まれません。そのため、urlモジュールを導入し、url.parse()メソッドを使用してアドレスをパラメータのないアドレスに解析する必要があります。
完全なコード:
// app.js
const http = require('http'); // 加载http服务模块
const fs = require('fs');
const path = require('path');
const url = require('url');
const common = require('./moudle/common');
http.createServer(function (req, res) {
// http://127.0.0.1:3000/login.html
// 1. 获取地址
let pathName = url.parse(req.url).pathname;
pathName = pathName == '/' ? '/index.html' : pathName;
// 获取后缀名 path.extname();
let extname = path.extname(pathName)
// 2. 通过fs模块读取文件
if(pathName != '/favicon.ico'){
fs.readFile(`./static${
pathName}`,(err,data) => {
if(err){
fs.readFile('./static/404.html',(err,data404)=>{
if(err){
console.log('404')
}else{
res.writeHead(404, {
'Content-Type': 'text/html;charset="utf-8"'});
res.end(data404);
}
})
}else{
let mime = common.getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
res.writeHead(200, {
'Content-Type': `${
mime};charset="utf-8"`});
res.end(data);
}
})
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
結果を図に示します。
2.静的WEBサーバーをカプセル化します
上の図に示すように、NODEJSディレクトリの下に新しいstaticApp.jsを作成し、moudleディレクトリの下に新しいroute.jsを作成して、静的Webサーバーをカプセル化します。
// route.js
const fs = require('fs');
const path = require('path');
const url = require('url');
// 私有方法
function getFileMime(extName){
// readFileSync 为 readFile 的同步方法
let data = fs.readFileSync('./data/mime.json'); // 注意:因为该方法在 app.js 引用,所以相对位置应以app.js为基点
let mimeObj = JSON.parse(data.toString());
return mimeObj[extName]
}
exports.static = (req,res,staticPath) => {
// 1. 获取地址
let pathName = url.parse(req.url).pathname;
pathName = pathName == '/' ? '/index.html' : pathName;
// 获取后缀名 path.extname();
let extname = path.extname(pathName)
// 2. 通过fs模块读取文件
if(pathName != '/favicon.ico'){
fs.readFile(`./${
staticPath}${
pathName}`,(err,data) => {
if(err){
fs.readFile('./static/404.html',(err,data404)=>{
if(err){
console.log('404')
}else{
res.writeHead(404, {
'Content-Type': 'text/html;charset="utf-8"'});
res.end(data404);
}
})
}else{
let mime = getFileMime(extname) // 根据对应的后缀名,获取对应的文件格式
res.writeHead(200, {
'Content-Type': `${
mime};charset="utf-8"`});
res.end(data);
}
})
}
}
// staticApp.js
const http = require('http'); // 加载http服务模块
const routes = require('./moudle/routes')
http.createServer(function (req, res) {
routes.static(req,res,'static')
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
結果を図に示します。