参考:http://www.runoob.com/nodejs/nodejs-web-module.html
1. 创建node项目目录 /home/data/node/firstNodeApi/ 并跳转到此目录下
# cd /home/data/node/firstNodeApi/
2. 创建服务端文件api.js
# vim api.js --创建并打开api.js文件
按 i --进入编辑状态,输入以下内容
var http = require('http');
var fs = require('fs');
var url = require('url');
http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for "+pathname+"received.");
fs.readFile(pathname.substr(1),function(err,data){
if(err){
console.log(err);
response.writeHead(404,{'Content-Type':'text/html'});
}else{
response.writeHead(200,{'Content-Type':'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8888);
console.log('Server running at http://192.168.96.131:8888');
按 esc 键 退出编辑状态
按 :wq 保存并退出
3.添加一个html文件 index.html
# vim index.html --创建并打开index.html文件
按 i --进入编辑状态,输入以下内容
<html>
<head>
<meta charset='utf-8'/>
<title>first node</title>
</head>
<body>
<h1>this is first node mode</h1>
<p>这是第一个node项目<p><button onclick="" value="获取百度" />
</body>
</html>
按 esc 键 退出编辑状态
按 :wq 保存并退出
4.启动服务
# node /home/data/node/firstNodeApi/api.js
在浏览器输入http://192.168.96.131:8888/index.html 检查是否成功