zoukankan      html  css  js  c++  java
  • 初识路由

    var fs = require('fs');
    var http = require('http');
    var server = http.createServer(function (req, res) {
        if(req.url !== '/favicon.ico'){
            console.log('客户端想服务器发送请求: '+ req.url);
            if (req.url === '/home' || req.url === '/'){
                res.writeHead(200,{'content-Type':'text/html'});
                fs.createReadStream(__dirname + '/home.html').pipe(res);
            }else if(req.url === '/contact'){
                res.writeHead(200,{'content-Type':'text/html'});
                fs.createReadStream(__dirname + '/contact.html').pipe(res);
            }else if(req.url === '/api'){
                res.writeHead(200,{'content-Type':'application/json'});
                var data=[{name:'henry',age:28},{name:'bucky',age:18}];
                res.end(JSON.stringify(data));
            }else{
                res.writeHead(200,{'conten-Type':'text/html'});
                fs.createReadStream(__dirname + '/error.html').pipe(res);
            }
        }
    });
    server.listen(3000,'127.0.0.1');
    console.log('server is running....');
    

    步骤:

    1. 引入文件系统模块
    2. 引入http模块
    3. 创建服务器
      3.1 判断req.url值
      3.2 设置协议头
      3.3 读取文件地址并使用管道流插入
    4. 监听服务器
  • 相关阅读:
    LINUX系列:Shell命令
    java程序猿必须掌握的4种线程池
    JAVA编程:Lock线程锁
    Spring框架之IOC的基本配置
    浅谈Java中的内部类
    [XDFZDay2]NOIP模拟
    [XDFZ集训Day1]NOI2020模拟1
    CSP2019游记
    11.11-11.12 CSP模拟总结
    [BJOI2019]排兵布阵
  • 原文地址:https://www.cnblogs.com/webarn/p/6380156.html
Copyright © 2011-2022 走看看