node.js学习笔记(3)_极客学院_服务器入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014267209/article/details/52083688

一.使用Http模块创建Web服务器

1.Node.js的Web服务器的特点:

    不依赖其他特定的Web服务器软件
    Node.js代码处理请求的逻辑
    Node.js代码负责Web服务器的各种'配置'
    var http = require('http'); // 引入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'); // 引入express模块

var app = express();

app.use(express.static('./public'));//静态文件的处理,localhost:3000/test.txt


// 三种不同的路由配置
//--------------------------------Path
app.get('/',function (req,res) {
    res.end('Hello');
});
//--------------------------------多个子路由
var Router = express.Router();
// http://exaample.com/post/add
// http://exaample.com/post/list

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);
//--------------------------------//RESTful接口
app.route('/article')
    .get(function (req,res) {
        res.end('Router /article get\n');
    })
    .post(function (req,res) {
        res.end('Router /article post\n');
    })
//--------------------------------// 另一种风格的路径处理
//e.g:http://example.com/news/123
app.param('newsId',function (req,res,next,newsId) {
    req.newsId = 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'); // 引入http模块

    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);

猜你喜欢

转载自blog.csdn.net/u014267209/article/details/52083688