zoukankan      html  css  js  c++  java
  • nodejs的简单服务器程序

    下面是参考<Jquery、Jquery UI 及Jquery Mobile>一书中的nodej服务器程序

    var http = require('http'),
        url = require('url'),
        fs = require('fs');
    http.createServer(function (req, res) {
      var reqData = {
            url: url.parse(req.url, true),
            method: req.method,
            headers: req.headers },
            path = reqData.url.pathname;
    
      if(path.match(/^/[0-9a-z-]+.(html)|(json)|(xml)$/))
        fs.readFile('.' + path, function (err, data) {
          if (err) {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('not found');
          }
          else {
           if(path.split('.')[1] == 'html')
               res.writeHead(200, {'Content-Type': 'text/html'});
           else if(path.split('.')[1] == 'xml')
               res.writeHead(200, {'Content-Type': 'application/xml'});
           else 
             res.writeHead(200, {'Content-Type': 'application/json'});
           res.end(data);
          }   
        });
      else if(path == '/return-http-headers') {
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(reqData));
      }
      else if(path == '/sleep') {
        var endTime = new Date().getTime() + 2000;
        while (new Date().getTime() < endTime);
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('slow response');
      }
      else if(path == '/validate') {
        var keys = [];
        for(var key in reqData.url.query) {
            if(reqData.url.query[key] == '')
                keys.push(key);
        }
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(keys));
      }
      else if(path == '/redirect') {
        res.writeHead(302, {
          'Location': '/test-values.json' });
        res.end();    
      }
      else if(path == '/fail-on-purpose') {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('unexpected" error');
      }
      else {
       res.writeHead(404, {'Content-Type': 'text/plain'});
       res.end('not found');
      }
    }).listen(1337, "localhost");
    console.log('Server running at http://localhost:1337/');
  • 相关阅读:
    禁止input密码自动填充及浏览器记住密码完整解决方案
    修改微信小程序的原生button样式
    css 多行超长点点点
    Vue中如何导入并读取Excel数据
    微信小程序 页面打开时scrollview动态滚动到指定位置
    :class和:style的三元表达式
    Vue3.0手机端页面适配屏幕px2rem(自动将px转化为rem)
    9.JavaScript内置对象
    8.JavaScript对象
    7.JavaScript 预解析
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4965940.html
Copyright © 2011-2022 走看看