NodeJS学习笔记之Http模块

首先“Http”这个概念大家应该比较熟悉了,它不是基于特定语言的,是一个通用的应用层协议,不同语言有不同的实现细节,但是万变不离其宗,思想是相同的,

NodeJS作为一个宿主运行环境,以JavaScript为宿主语言,它也有自己实现的一套标准,这篇文章我们就一起来学习一下 “Http模块” 。但是作为前提来说,

希望大家可以先阅读一下官网提供的api,有一个前置了解,这样就方便多了,以下是Http部分的api概览:

复制代码 代码如下:


HTTP
    http.STATUS_CODES
    http.createServer([requestListener])
    http.createClient([port], [host])
    Class: http.Server
    事件 : 'request'
    事件: 'connection'
    事件: 'close'
    Event: 'checkContinue'
    事件: 'connect'
    Event: 'upgrade'
    Event: 'clientError'
    server.listen(port, [hostname], [backlog], [callback])
    server.listen(path, [callback])
    server.listen(handle, [callback])
    server.close([callback])
    server.maxHeadersCount
    server.setTimeout(msecs, callback)
    server.timeout
    Class: http.ServerResponse
        事件: 'close'
        response.writeContinue()
        response.writeHead(statusCode, [reasonPhrase], [headers])
        response.setTimeout(msecs, callback)
        response.statusCode
        response.setHeader(name, value)
        response.headersSent
        response.sendDate
        response.getHeader(name)
        response.removeHeader(name)
        response.write(chunk, [encoding])
        response.addTrailers(headers)
        response.end([data], [encoding])
        http.request(options, callback)
        http.get(options, callback)
    Class: http.Agent
        new Agent([options])
        agent.maxSockets
        agent.maxFreeSockets
        agent.sockets
        agent.freeSockets
        agent.requests
        agent.destroy()
        agent.getName(options)
        http.globalAgent
    Class: http.ClientRequest
        Event 'response'
        Event: 'socket'
        事件: 'connect'
        Event: 'upgrade'
        Event: 'continue'
        request.write(chunk, [encoding])
        request.end([data], [encoding])
        request.abort()
        request.setTimeout(timeout, [callback])
        request.setNoDelay([noDelay])
        request.setSocketKeepAlive([enable], [initialDelay])
    http.IncomingMessage
        事件: 'close'
        message.httpVersion
        message.headers
        message.rawHeaders
        message.trailers
        message.rawTrailers
        message.setTimeout(msecs, callback)
        message.method
        message.url
        message.statusCode
        message.socket

让我们先从一个简单例子开始,创建一个叫server.js的文件,并写入以下代码:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxwpp.html