zoukankan      html  css  js  c++  java
  • node.js在windows下的学习笔记(5)---用NODE.JS创建服务器和客户端

    //引入http模块
    var http = require('http');
    //调用http的createServer的方法,这个方法有一个回调函数,这个回调数
    //的作用是当有请求发送给服务器的时候,就执行这个回调函数
    http.createServer(function (req, res) {
      //发送
      res.end('Hello World
    ');
    }).listen(3000, "127.0.0.1");//端口和IP的绑定
    console.log('Server running at http://127.0.0.1:3000/');

    以上代码,创建了一个服务器,并设置了发送给客户端的内容,下面讲一下Node.js中的重定向

    var http = require('http');
    http.createServer(function (req, res) {
      //重定向,writeHead方法
      res.writeHead(301, {
        'Location': 'http://www.baidu.com'
      });
        res.end();
    }).listen(3000, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:3000/');

    通过设置路由,来响应不同的请求(本质),这里,其实会越来越复杂的,因为如果有很多种类的响应的话,if--else会越来越多,后面会介绍一下Express框架

    var http = require('http'),
        url = require('url');
    
    http.createServer(function (req, res) {
      //解析URL,取得路径名
      var pathname = url.parse(req.url).pathname;
    
      if (pathname === '/') {
          res.writeHead(200, {
          'Content-Type': 'text/plain'
        });
        res.end('Home Page
    ')
      } else if (pathname === '/about') {
          res.writeHead(200, {
          'Content-Type': 'text/plain'
        });
        res.end('About Us
    ')
      } else if (pathname === '/redirect') {
          res.writeHead(301, {
          'Location': '/'
        });
        res.end();
      } else {
          res.writeHead(404, {
          'Content-Type': 'text/plain'
        });
        res.end('Page not found
    ')
      }
    }).listen(3000, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:3000/');

    用Node.js创建一个客户端

    var http = require('http');
    
    var options = {
      host: 'shapeshed.com',
      port: 80,
      path: '/'
    };
    
    http.get(options, function(res) {
      if (res.statusCode  == 200) {
        console.log("The site is up!");
      }
      else {
        console.log("The site is down!");
      }
    }).on('error', function(e) {
      console.log("There was an error: " + e.message);
    });
  • 相关阅读:
    etcd 部署、备份与恢复
    centos7 mysql 5.7.24 源码编译
    生产中两块网卡bond
    shell 免密批量执行脚本
    MegaCli 清除与添加raid5
    centos7 mongodb4.0.2 复制集主从部署
    centos6.6 部署 cacti 并采集交换机流量
    shell 批量远程主机执行命令
    拯救系统文件只读模式
    下推自动机(PDA)在程序设计中的应用
  • 原文地址:https://www.cnblogs.com/michaeljunlove/p/3972065.html
Copyright © 2011-2022 走看看