const http = require("http");
const fs = require("fs");
function startServer(){
let create = function (req, res){
if (req.url === "/" || req.url === "/home" ){
res.writeHead(200,{"Content-Type":'text/html'});
fs.createReadStream(__dirname+"/Hello.html",'utf8').pipe(res);
}else if (req.url === "/index"){
res.writeHead(200,{"Content-Type":'text/html'});
fs.createReadStream(__dirname+"/Index.html",'utf8').pipe(res);
}else if (req.url === "/json"){
res.writeHead(200,{"Content-Type":'application/json'});
const json = {
name:"king",
age:34
}
res.end(JSON.stringify(json));
}else{
res.writeHead(404,{"Content-Type":'text/html'});
fs.createReadStream(__dirname+"/404.html",'utf8').pipe(res);
}
}
let server = http.createServer(create);
server.listen(3000,'127.0.0.1');
console.log("server started on localhost port 3000");
}
exports.startServer = startServer;
startServer();
nodejs路由<一>
最新推荐文章于 2025-01-09 09:37:01 发布
该代码创建了一个Node.js服务器,监听3000端口。根据请求的URL,服务器返回不同内容:根目录和/home路由返回Hello.html,/index路由返回Index.html,/json路由返回JSON对象,其他未定义的路由返回404错误页面。
184

被折叠的 条评论
为什么被折叠?



