Node.js 搭建web服務(wù)器
服務(wù)端腳本
1. Nodejs搭建web服務(wù)器響應(yīng)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服務(wù)器響應(yīng)html靜態(tài)文件
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. 運(yùn)行服務(wù)端Node.js腳本
node app.js
客戶端瀏覽器訪問(wèn)
http://172.16.0.130:3000
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者