我正在尝试使用node(我是node.JS的新手(创建一个简单的服务器
- 服务器正在工作
- 能够读取html、css和js文件的内容
- 我面临的问题是服务器只返回url上的html文件(localhost:8000(
- 如果我输入url:localhost:8000/css,它会返回实际代码的css文件的数据
- 与localhost:8000/js相同,返回代码
- 我希望它使用html、css和js返回完整的页面
请在这里指引我。。
var http = require('http');
var fs = require('fs');
var htmlData, cssData, jsData;
fs.readFile('index.html',(err, data)=>{
if(err){
htmlData = err;
}
htmlData = data;
});
fs.readFile('style.css',(err, data)=>{
if(err){
cssData = err;
}
cssData = data;
});
fs.readFile('index.js',(err, data)=>{
if(err){
jsData = err;
}
jsData = data;
});
const httpServer = http.createServer(serverHandler);
function serverHandler(req, res) {
// add a HTTP header:
switch (req.url) {
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(htmlData); //read the file & write the data content
res.end();
break;
case '/style':
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(cssData); //read the file & write the data content
res.end();
break;
case '/js':
res.writeHead(200, {'Content-Type': 'text/js'});
res.write(jsData); //read the file & write the data content
res.end();
break;
default:
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('error'); //read the file & write the data content
res.end();
break;
}
}
httpServer.listen(8000,()=>{console.log("PORT is 8000")});
你几乎自己达到了目标
只需将实际文件名放入switch case
语句中,如下所示:
将case '/js':
编辑为case '/index.js'
,并将css的case '/style':
编辑为case '/style.css':
。
您的http请求应该与文件的实际名称相匹配。