美文网首页
Node.js静态请求(8.9)

Node.js静态请求(8.9)

作者: Tarek | 来源:发表于2016-08-10 13:59 被阅读0次

    创建服务器

    const http = require('http');
    const ip = '192.168.169.129';
    const port = 3000;
    
    var f = function(req,res){
    res.writeHead(200,{'Content-Type':'text/plain'});
    res.write("Hello !");
    res.end();
    }
    
    var f2 = function(){
    console.log('server start');
    }
    
    var server = http.createServer(f);
    server.listen(port,ip,f2);
    

    添加URL内容

    const http = require('http');
    const ip = '192.168.169.129';
    const port = 3000;
    const url = require('url');
    
    var f = function(req,res){
      var path = url.parse(req.url).pathname;
      res.write(path);
      res.end();
    }
    
    var f2 = function(){
      console.log('server start');
    }
    
    var server = http.createServer(f);
    server.listen(port,ip,f2);
    

    读取File

    const http = require('http');
    const ip = '192.168.169.129';
    const port = 3000;
    const fs = require('fs');
    
    var f3 = function(err,data){
      console.log(data.toString());
    }
    
    fs.readFile('q.index.html',f3);
    
    var f = function(req,res){
      res.writeHead(200,{'Content-Type':'text/html'})
      res.write("Hello Kitty !");
      res.end();
    }
    
    var f2 = function(){
      console.log('server start');
    }
    
    var server = http.createServer(f);
    server.listen(port,ip,f2);
    

    浏览器输出文件内容

    const http = require('http');
    const ip = '192.168.169.129';
    const port = 3000;
    const url = require('url');
    const fs = require('fs');
    
    var data = fs.readFileSync('./index.html');
    
    var f = function(req,res){
      var path = url.parse(req.url).pathname;
      res.write(path);
      res.write(data.toString());
      res.end();
    }
    
    var f2 = function(){
      console.log('server start');
    }
    
    var server = http.createServer(f);
    server.listen(port,ip,f2);

    相关文章

      网友评论

          本文标题:Node.js静态请求(8.9)

          本文链接:https://www.haomeiwen.com/subject/njfjsttx.html