• 创建一个服务器,解析当前的url并根据url并作出相应的响应


    /*
    * 实例说明:
    * 1、创建一个服务器;
    * 2、解析当前的url;
    * 3、根据url并作出相应的响应
    */


    var http=require("http");
    //导入文件模块
    var fs=require("fs");
    var url=require("url");
    var server =http.createServer(function(req,res){

    //使用req.url获取当前url,注:url在使用时,需要用url.parse进行解析
    var urlObj=url.parse(req.url);
    var pathname=urlObj.pathname;

    //在控制台输出当前的pathname
    // console.log(pathname);

    //判断pathname,进行相应路径的跳转
    if(pathname=="/"){
    goPage("/index.html",res);
    }
    else if(pathname=="/login.html"){
    goPage(pathname,res);
    }
    else {
    goPage(pathname,res);
    }

    //监听端口,注:一个程序只能监听一个端口
    }).listen(8888);

    //判断pathname,响应并返回相应页面
    function goPage(pathname,res){
    fs.readFile(pathname.substr(1),"utf-8",function(err,data) {
    if(err){

    //在控制台打印出错误信息
    //console.log("Error:"+err);

    // //修改header状态码,返回404页面
    res.writeHeader("404");

    //调用404页面(notFound.html)
    fs.readFile('notFound.html', 'utf-8', function(err, data) {
    res.end(data.toString());
    });
    }else{
    //设置头信息
    res.setHeader("Content-Type","text/html;charset='utf-8'");
    //返回index.html页面
    res.end(data);
    }
    });
    }
  • 相关阅读:
    oracle 如何用触发器实现更新刚插入的数据
    数据库好论坛
    不同的用户导入数据库
    用函数式编程技术编写优美的 JavaScript
    使用GridView自带的ToolTip隐藏过长的数据
    含有dropdownlist的gridview增删改查
    数据分析
    数据分析
    xshell链接vbox 上 nat 方式链接虚拟机
    测试开发方法概述
  • 原文地址:https://www.cnblogs.com/shenyulin/p/4447645.html
Copyright © 2020-2023  润新知