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);
    });
  • 相关阅读:
    洛谷 P1443 马的遍历 BFS
    洛谷 P1583 魔法照片 快排
    洛谷 P1093 奖学金 冒泡排序
    洛谷 P3811 【模板】乘法逆元 如题
    洛谷 P3384 【模板】树链剖分 如题
    洛谷 P3379 【模板】最近公共祖先(LCA) 如题
    vijos 信息传递 tarjan找环
    洛谷 P3373 【模板】线段树 2 如题(区间加法+区间乘法+区间求和)
    酒厂选址
    ⑨要写信
  • 原文地址:https://www.cnblogs.com/michaeljunlove/p/3972065.html
Copyright © 2011-2022 走看看