zoukankan      html  css  js  c++  java
  • Nodejs Web模块( readFile 根据请求跳转到响应html )

    index.js

    根据请求的路径pathname,返回响应的页面。

    var http = require('http');
    var fs = require('fs');
    var url = require('url');
    
    
    // 创建服务器
    http.createServer( function (request, response) {  
       // 解析请求,包括文件名
       var pathname = url.parse(request.url).pathname;
       
       // 输出请求的文件名
       console.log("Request for " + pathname + " received.");
       
       // 从文件系统中读取请求的文件内容
       fs.readFile(pathname.substr(1), function (err, data) {
          if (err) {
             console.log(err);
             // HTTP 状态码: 404 : NOT FOUND
             // Content Type: text/plain
             response.writeHead(404, {'Content-Type': 'text/html'});
          }else{	         
             // HTTP 状态码: 200 : OK
             // Content Type: text/plain
             response.writeHead(200, {'Content-Type': 'text/html'});	
             
             // 响应文件内容
             response.write(data.toString());		
          }
          //  发送响应数据
          response.end();
       });   
    }).listen(3000);
    
    // 控制台会输出以下信息
    console.log('Server running at http://127.0.0.1:3000/');
    

      

    index.html

    <html>
    <head>
    <title>Sample Page</title>
    </head>
    <body>
    Hello World!
    </body>
    </html>
    

      

    浏览器中打开: http://127.0.0.1:3000/index.html

    页面显示  index.html

  • 相关阅读:
    For each db / table
    转---网络上来的,做一个数组样的结构
    JAVA 相关资料
    转--也不知是哪位大侠写的了
    T-SQL切割字符串方法小结 2
    OPENQUERY
    行集函数专题
    行列转换
    第一章 SQL基础
    解释型语言与编译型语言的区别
  • 原文地址:https://www.cnblogs.com/gamedaybyday/p/6638804.html
Copyright © 2011-2022 走看看