Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js http Module

Node.js http Module

Java FileNode.js Built-in Modules


Node.js's http The module is one of Node.js's built-in core modules; it allows developers to create HTTP servers and clients. Through this module, we can easily handle HTTP requests and responses, and build web applications or API services.

http The module provides the ability to create servers and initiate HTTP requests, and is the foundation for building web applications. It supports the HTTP/1.1 protocol and provides a rich set of APIs to handle various HTTP-related operations.


Create an HTTP server

Use http Creating a server with the module is very simple; here is the most basic example:

Example

const

http

=

require

(

'http'

)

;

// Create an HTTP server

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

// Set response headers

  res.

writeHead

(

200

,

{

'Content-Type'

:

'text/plain'

}

)

;

 

 

// Send response data

  res.

end

(

'Hello, World!\n'

)

;

}

)

;

// Listen on port 3000

server.

listen

(

3000

,

(

)

=>

{

  console.

log

(

'Server running at http://localhost:3000/'

)

;

}

)

;

Code Analysis

  1. require('http') - Import Node.js's http module
  2. http.createServer() - Create an HTTP server instance
  3. Callback Function (req, res) => {...} - Handle every HTTP request
  4. req - Request object, containing information about the request sent by the client
  5. res - Response object, used to send responses to the client
  6. - `req` - request object, containing information about the request sent by the client - `res` - response object, used to send responses to the client
    1. res.writeHead() - Set response headers
    2. res.end() - End the response and send data
    3. server.listen() - Start the server listening on a specified port

    Handling HTTP Requests

    An HTTP server needs to be able to handle different types of requests. Let's look at how to parse request information:

    Example

    const

    http

    =

    require

    (

    'http'

    )

    ;

    const

    server

    =

    http.

    createServer

    (

    (

    req

    ,

    res

    )

    =>

    {

     

    // Get the request method, URL, and headers

     

    const

    {

    method

    ,

    url

    ,

    headers

    }

    =

    req

    ;

     

     

    // Log the request information

      console.

    log

    (

    `Received $

    {

    method

    }

    request, path

    :

    $

    {

    url

    }

    `

    )

    ;

      console.

    log

    (

    'Request headers:'

    ,

    headers

    )

    ;

     

     

    // Handle according to the request method

     

    if

    (

    method

    ===

    'GET'

    )

    {

        res.

    writeHead

    (

    200

    ,

    {

    'Content-Type'

    :

    'text/plain'

    }

    )

    ;

        res.

    end

    (

    'This is a GET request\n'

    )

    ;

     

    }

    else

    if

    (

    method

    ===

    'POST'

    )

    {

        let body

    =

    ''

    ;

       

       

    // Collect POST data

        req.

    on

    (

    'data'

    ,

    chunk

    =>

    {

          body

    +=

    chunk

    ;

       

    }

    )

    ;

       

       

    // Data reception complete

        req.

    on

    (

    'end'

    ,

    (

    )

    =>

    {

          console.

    log

    (

    'POST data:'

    ,

    body

    )

    ;

          res.

    writeHead

    (

    200

    ,

    {

    'Content-Type'

    :

    'text/plain'

    }

    )

    ;

          res.

    end

    (

    'Data received\n'

    )

    ;

       

    }

    )

    ;

     

    }

    else

    {

        res.

    writeHead

    (

    405

    ,

    {

    'Content-Type'

    :

    'text/plain'

    }

    )

    ;

        res.

    end

    (

    'Method not allowed\n'

    )

    ;

     

    }

    }

    )

    ;

    server.

    listen

    (

    3000

    )

    ;

    Common Properties of the Request Object (req)

    Common Methods of the Response Object (res)


    Make an HTTP request

    http The module can not only create servers but also act as a client to initiate HTTP requests:

    Example

    const

    http

    =

    require

    (

    'http'

    )

    ;

    // Initiate a GET request

    http.

    get

    (

    'http://jsonplaceholder.typicode.com/posts/1'

    ,

    (

    res

    )

    =>

    {

      let data

    =

    ''

    ;

     

     

    // Receive data

      res.

    on

    (

    'data'

    ,

    (

    chunk

    )

    =>

    {

        data

    +=

    chunk

    ;

     

    }

    )

    ;

     

     

    // Data reception complete

      res.

    on

    (

    'end'

    ,

    (

    )

    =>

    {

        console.

    log

    (

    'Response data:'

    ,

    JSON.

    parse

    (

    data

    )

    )

    ;

     

    }

    )

    ;

    }

    )

    .

    on

    (

    'error'

    ,

    (

    err

    )

    =>

    {

      console.

    error

    (

    'Request error:'

    ,

    err

    )

    ;

    }

    )

    ;

    Initiating a POST Request

    Example

    const

    http

    =

    require

    (

    'http'

    )

    ;

    // Request options

    const

    options

    =

    {

      hostname

    :

    'jsonplaceholder.typicode.com'

    ,

      port

    :

    80

    ,

      path

    :

    '/posts'

    ,

      method

    :

    'POST'

    ,

      headers

    :

    {

       

    'Content-Type'

    :

    'application/json'

    ,

     

    }

    }

    ;

    // Create the request

    const

    req

    =

    http.

    request

    (

    options

    ,

    (

    res

    )

    =>

    {

      let data

    =

    ''

    ;

     

      res.

    on

    (

    'data'

    ,

    (

    chunk

    )

    =>

    {

        data

    +=

    chunk

    ;

     

    }

    )

    ;

     

      res.

    on

    (

    'end'

    ,

    (

    )

    =>

    {

        console.

    log

    (

    'Response:'

    ,

    JSON.

    parse

    (

    data

    )

    )

    ;

     

    }

    )

    ;

    }

    )

    ;

    // Handle errors

    req.

    on

    (

    'error'

    ,

    (

    err

    )

    =>

    {

      console.

    error

    (

    'Request error:'

    ,

    err

    )

    ;

    }

    )

    ;

    // Write request data

    const

    postData

    =

    JSON.

    stringify

    (

    {

      title

    :

    'foo'

    ,

      body

    :

    'bar'

    ,

      userId

    :

    1

    }

    )

    ;

    req.

    write

    (

    postData

    )

    ;

    req.

    end

    (

    )

    ;


    Practical Application Scenarios

    1. Create a RESTful API

    Example

    const

    http

    =

    require

    (

    'http'

    )

    ;

    const

    server

    =

    http.

    createServer

    (

    (

    req

    ,

    res

    )

    =>

    {

     

    const

    {

    method

    ,

    url

    }

    =

    req

    ;

     

     

    // Simple routing handling

     

    if

    (

    method

    ===

    'GET'

    &&

    url

    ===

    '/api/users'

    )

    {

        res.

    writeHead

    (

    200

    ,

    {

    'Content-Type'

    :

    'application/json'

    }

    )

    ;

        res.

    end

    (

    JSON.

    stringify

    (

    [

    {

    id

    :

    1

    ,

    name

    :

    'Alice'

    }

    ,

    {

    id

    :

    2

    ,

    name

    :

    'Bob'

    }

    ]

    )

    )

    ;

     

    }

    else

    if

    (

    method

    ===

    'POST'

    &&

    url

    ===

    '/api/users'

    )

    {

        let body

    =

    ''

    ;

        req.

    on

    (

    'data'

    ,

    chunk

    =>

    body

    +=

    chunk

    )

    ;

        req.

    on

    (

    'end'

    ,

    (

    )

    =>

    {

         

    const

    newUser

    =

    JSON.

    parse

    (

    body

    )

    ;

         

    // Here you can save to a database

          res.

    writeHead

    (

    201

    ,

    {

    'Content-Type'

    :

    'application/json'

    }

    )

    ;

          res.

    end

    (

    JSON.

    stringify

    (

    {

    id

    :

    Date

    .

    now

    (

    )

    ,

    ...

    newUser

    }

    )

    )

    ;

       

    }

    )

    ;

     

    }

    else

    {

        res.

    writeHead

    (

    404

    ,

    {

    'Content-Type'

    :

    'text/plain'

    }

    )

    ;

        res.

    end

    (

    'Not Found\n'

    )

    ;

     

    }

    }

    )

    ;

    server.

    listen

    (

    3000

    )

    ;

    2. Proxy Server

    Example

    const

    http

    =

    require

    (

    'http'

    )

    ;

    const

    proxy

    =

    http.

    createServer

    (

    (

    clientReq

    ,

    clientRes

    )

    =>

    {

     

    // Initiate a request to the target server

     

    const

    options

    =

    {

        hostname

    :

    'example.com'

    ,

        port

    :

    80

    ,

        path

    :

    clientReq.

    url

    ,

        method

    :

    clientReq.

    method

    ,

        headers

    :

    clientReq.

    headers

     

    }

    ;

     

     

    const

    proxyReq

    =

    http.

    request

    (

    options

    ,

    (

    proxyRes

    )

    =>

    {

       

    // Forward the target server's response to the client

        clientRes.

    writeHead

    (

    proxyRes.

    statusCode

    ,

    proxyRes.

    headers

    )

    ;

        proxyRes.

    pipe

    (

    clientRes

    )

    ;

     

    }

    )

    ;

     

     

    // Forward the client's request body

      clientReq.

    pipe

    (

    proxyReq

    )

    ;

    }

    )

    ;

    proxy.

    listen

    (

    8080

    )

    ;


    Best Practices

    1. Error handling: Always handle error events in requests and responses
    2. Performance considerations: For high-concurrency applications, consider using a connection pool
    3. Safety:
    4. Validate all input
    5. Set appropriate security headers
    6. Limit request body size to prevent DoS attacks
    7. - Validate all input - Set appropriate security headers - Limit request body size to prevent DoS attacks
      1. Use streams: For large file transfers, use stream processing
      2. Consider frameworks: For complex applications, consider using frameworks such as Express and Koa

      Summary

      Node.js's http The module provides the fundamental capabilities for building network applications. Although many more advanced frameworks are available today, understanding http how the module works is essential for any Node.js developer. By mastering this core module, you can gain a better understanding of how web applications work and build custom solutions to meet your needs.

      Java FileNode.js Built-in Modules