首页 > Web开发 > 详细

node.js 配置首页打开页面

时间:2017-07-11 17:14:24      阅读:670      评论:0      收藏:0      [点我收藏+]

/*var http = require(‘http‘);
var fs = require(‘fs‘);
var url = require(‘url‘);

var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
console.log("nodejs start listen 8888 port!");
*/
var express= require("express");
var fs = require(‘fs‘);
var documentRoot = ‘D:/Program Files/nodejs/www‘;
var app=express();
app.get(‘/‘,function(req,res){
var url = req.url;
var file=documentRoot+url+"index.html";
//res.send("Hello word");
fs.readFile( file , function(err,data){
/*
一参为文件路径
二参为回调函数
回调函数的一参为读取错误返回的信息,返回空就没有错误
二参为读取成功返回的文本内容
*/
if(err){
res.writeHeader(404,{
‘content-type‘ : ‘text/html;charset="utf-8"‘
});
res.write(‘<h1>404错误</h1><p>你要找的页面不存在</p>‘);
res.end();
}else{
res.writeHeader(200,{
‘content-type‘ : ‘text/html;charset="utf-8"‘
});
res.write(data);//将index.html显示在客户端
res.end();
}
});
})
app.listen(8888,function(){
console.log("现在端口是8888");

})

 编辑完后 在命令行node 当前js名.js

node.js 配置首页打开页面

原文:http://www.cnblogs.com/itadong/p/7151406.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!