Node.js 搭建web服务器
服务端脚本
1. Nodejs搭建web服务器响应html
const http = require('http');
const url = require('url');
const ip = '172.16.0.130';
const port = 3000;
var f = function(req, res){
var reqUrl = url.parse(req.url);
console.log(reqUrl.pathname);
res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
res.write('<h1>ok</h1>');
res.end();
}
var serverMsg = function(){
console.log('Server Start !');
}
http.createServer(f).listen(port, ip, serverMsg);
2. Node.js搭建web服务器响应html静态文件
app.js文件:
const http = require('http');
const url = require('url');
const fs = require('fs');
const ip = '172.16.0.130';
const port = 3000;
var f = function(req, res){
var reqUrl = url.parse(req.url);
console.log(reqUrl.pathname);
switch (reqUrl.pathname) {
case '' || '/' || 'index':
fs.readFile('index.html', function(err, data){
//console.log(data);
//res.write(data.toString());
if(err){
console.log(err);
}else{
res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
res.write(data.toString());
res.end();
}
});
break;
default:
}
}
var serverMsg = function(){
console.log('Server Start !');
}
http.createServer(f).listen(port, ip, serverMsg);
index.html 文件:
<h1>hello YF</h1>
3. 运行服务端Node.js脚本
node app.js
客户端浏览器访问
http://172.16.0.130:3000