一.使用Http模块创建Web服务器
1.Node.js的Web服务器的特点:
不依赖其他特定的Web服务器软件
Node.js代码处理请求的逻辑
Node.js代码负责Web服务器的各种'配置'
var http = require('http');
var requestHandler = function (req ,res ) {
console.log('hahahaha');
res.end('hello');
};
var web = http.createServer(requestHandler);
web.listen(3000);
console.log("success: localhost:30000")
二.使用Express创建Web服务器
1.简单的Express服务器:
var http = require('express');
var app = express();
app.use(express.static('./public'));
app.get('/',function (req,res) {
res.end('Hello');
});
var Router = express.Router();
Router.get('/add',function (req,res) {
res.end('Router /add \n');
});
Router.get('/list',function (req,res) {
res.end('Router /list \n');
});
app.use('/post',Router);
app.route('/article')
.get(function (req,res) {
res.end('Router /article get\n');
})
.post(function (req,res) {
res.end('Router /article post\n');
})
app.param('newsId',function (req,res,next,newsId) {
req.newsId = newsId;
next();
});
app.get('/news/:newsId',function(req,res){
res.end('newsId"' + newsId);
})
app.listen(3000,function afterListen() {
console.log('express running on localhost:3000');
});
三.使用Net模块创建Tcp服务器
var net = require('net');
const PORT = '18000';
const HOST = '127.0.0.1';
var clientHandler = function (socket) {
console.log('someone connected');
socket.on('data',function dataHandler(data) {
console.log(socket._remoteAddress,socket.remotePort,'send',data.toString()) ;
socket.write('server received!');
})
socket.on('close',function dataHandler() {
console.log(socket._remoteAddress,socket.remotePort,'close') ;
})
};
var app = net.createServer(clientHandler);
app.listen(PORT,HOST);