zoukankan      html  css  js  c++  java
  • 函数传递是如何让HTTP服务器工作的

    带着这些知识,我们再来看看我们简约而不简单的HTTP服务器:

    var http = require("http"); //加载http模块
    
    http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write("Hello World");
      response.end();
    }).listen(8888);

    现在它看上去应该清晰了很多:我们向 createServer 函数传递了一个匿名函数。

    用这样的代码也可以达到同样的目的:

    var http = require("http");
    
    function onRequest(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write("Hello World");
      response.end();
    }
    
    http.createServer(onRequest).listen(8888);

    最清晰的思路是
    // 加载http模块
    var http = require('http');
    // 创建http服务
    var server = http.createServer();
    // 服务器对象监听客户端request事件
    server.on('request',function (req,res) {
    // req 代表请求对象 request
    // res 代表响应对象 response
    console.log('连接成功');
    res.setHeader("Content-type","text/html;charset=utf-8"); //响应为html文本
    res.end('哈哈哈,我捡到五毛钱。。。');//结束响应
    });
    // 启动http服务,监听端口
    server.listen('3000','10.36.135.97',function () {
    console.log('服务器启动成功');
    });
     
  • 相关阅读:
    跳转指定页面
    如何解决项目中.a文件中的.o冲突
    地图根据起点和终点计算中心点角度来绘制弧线 iOS
    codePush常用
    ios原生push到RN界面后pop
    atomic,nonatomic的区别
    KVC
    jQuery绑定event事件的各种方法比较
    Git常用命令总结
    多个$(document).ready()的执行顺序问题
  • 原文地址:https://www.cnblogs.com/shenlan88/p/11061887.html
Copyright © 2011-2022 走看看