nodejs静态html文件,node不利用框架怎么实现对静态HTML、css、js的服务?

初学nodeJS,在使用nodejs构建静态文件服务器的时候,遇到下面问题。

用户请求index.html时,我使用fs.readFile读取index.html并将data返回,代码如下:

function serverStatic(req,res){

var filePath;

if(req.url==="/"){

filePath = "index.html";

} else{

filePath = "./" + url.parse(req.url).pathname;

}

fs.exists(filePath,function(err){

if(err){

send404(res);

}else{

fs.readFile(filePath,function(err,data){

if(err){

res.end("

500

服务器内部错误!");

}else{

res.writeHead(200,{'content-type':'text/html'});

res.end(data.toString());

}

});//fs.readfile

}

})//path.exists

}//serverStatic

那么问题来了,如果我的HTML页面引用了外部的css或者js,那么这些外部文件不会被加载···

这个问题怎么解决?

尝试:

index源码:

看看伸缩盒?

css:

body{background-color:red;}

app.js:

var http=require('http');

var fs=require('fs');

var url=require('url');

var path=require('path');

var PORT=9090;

//添加MIME类型

var MIME_TYPE = {

"css": "text/css",

"gif": "image/gif",

"html": "text/html",

"ico": "image/x-icon",

"jpeg": "image/jpeg",

"jpg": "image/jpeg",

"js": "text/javascript",

"json": "application/json",

"pdf": "application/pdf",

"png": "image/png",

"svg": "image/svg+xml",

"swf": "application/x-shockwave-flash",

"tiff": "image/tiff",

"txt": "text/plain",

"wav": "audio/x-wav",

"wma": "audio/x-ms-wma",

"wmv": "video/x-ms-wmv",

"xml": "text/xml"

};

var server = http.createServer(serverStatic);

function serverStatic(req,res){

var filePath;

if(req.url==="/"){

filePath = "index.html";

} else{

filePath = "./" + url.parse(req.url).pathname;

}

fs.exists(filePath,function(err){

if(!err){

send404(res);

}else{

var ext = path.extname(filePath);

ext = ext?ext.slice(1) : 'unknown';

var contentType = MIME_TYPE[ext] || "text/plain";

fs.readFile(filePath,function(err,data){

if(err){

res.end("

500

服务器内部错误!");

}else{

res.writeHead(200,{'content-type':contentType});

res.end(data.toString());

}

});//fs.readfile

}

})//path.exists

}

server.listen(PORT);

console.log("Server runing at port: " + PORT + ".");

function send404(res){

res.end("

404

file not found

")

}

chrome查看网络:

bVsp17

我的文件结构

bVsp2f

bVsp2h

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值