Servidor HTTP

Nodejs nos permite crear servidores HTTP, para crear nuestro servidor HTTP necesitamos utilizar el módulo http y el metodo createServer()

const http = require('http')
const port = 3000

const server = http.createServer((request, response) => {
  response.end("Hello Nodejs")
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

El método createServer() nos devuelve un objeto http.Server el cual tenemos que definir con el método listen() del objeto sobre qué puerto en al sistema va a escuchar a la hora de procesar conexiones entrantes al sistema. Dentro del método createServer() tenemos dos parámetros importantes:

request - Este parámetro guarda información de la solicitud (request) al sistema.

response - Este parámetro es para poder manejar la respuesta a la solicitud al sistema.

Solicitud (Request)

Parámetro guarda información de la solicitud al sistema, este contiene propiedades como:

  • headers - nos devuelve la cabecera de la solicitud.

  • method - que tipo de solicitud.

  • url - representación de la dirección de la solicitud

Respuesta (Response)

Parámetros es para poder manejar la respuesta a la solicitud al sistema, este contiene métodos como:

  • statusCode - conjunto de codigo de respuesta.

  • statusMessage - conjunto de mensajes con código de respuesta.

  • setHeader(name, value) - Nos permite añadir cabecera a respuesta.

  • write - Nos permite escribir contenido y enviarlo como respuesta.

  • writeHead - Nos permite añadir código de estatus en cabecera de respuesta.

Interpretar rutas de solicitud (Parsing request paths)

const http = require('http')
const url = require('url')
const port = 3000

const server = http.createServer((request, response) => {
  // Get the URL and parse it 
  const 
    parsedUrl = url.parse(request.url, true)

  // Get the path 
  const 
    path = parsedUrl.pathname,
    trimmedPath = path.replace(/^\/+|\/+$/g,'')

  // Send the response 
  response.end('Hello Nodejs')

  // Log 
  console.log('Request received on path: ', trimmedPath)
  // GET - http://localhost:3000/foo
  //-> foo 
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

Interpretar métodos HTTP (Parsing HTTP methods)

const http = require('http')
const url = require('url')
const port = 3000

const server = http.createServer((request, response) => {
  // Get the HTTP method 
  const 
    method = request.method.toLowerCase()

  response.end('Hello Nodejs')

  // Log 
  console.log('Rquest received method: ', method)
  // GET - http://localhost:3000/foo
  //-> get
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

Interpretar cadenas de consulta (Parsing query string)

const http = require('http')
const url = require('url')
const port = 3000

const server = http.createServer((request, response) => {
  const 
    parsedUrl = url.parse(request.url, true)

  // Get the query string as an object
  const 
    queryStringObject = parsedUrl.query

  // Log 
  console.log('Request received query string: ', queryStringObject)
  // GET - http://localhost:3000/foo?buzz=fuz
  //-> Request received query string:  { buzz: 'fuz' }
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

Interpretar cabecera (Parsing headers)

const http = require('http')
const url = require('url')
const port = 3000

const server = http.createServer((request, response) => {
  // Get the headers as an object
  const headers = request.headers

  // Log 
  console.log('Request received headers: ', headers)
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

Interpretar payload (Parsing payloads)

const http = require('http')
const url = require('url')
const StringDecoder = require('string_decoder')
const port = 3000

const server = http.createServer((request, response) => {
  // Get the payload, if any
  const 
    decoder = new StringDecoder.StringDecoder('utf-8')

  let
    buffer = ''

  request.on('data', (data) => {
      buffer += decoder.write(data)
  })

  request.on('end', () => {
    buffer += decoder.end()

    response.end('Hello Nodejs')

    // Log 
    console.log('Request received with this payload: ', buffer)

    // Using Postman Tools
    // POST - http://localhost:3000/
    // Body Raw:
    //   - Text: "This is the body we are sending"
    //-> Request received with this payload:  This is the body we are sending
  })
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

Solicitud de enrutamiento (Routing request)

const http = require('http')
const url = require('url')
const StringDecoder = require('string_decoder')
const port = 3000

let handlers = {}

// Sample handler 
handlers.sample = (data, callback) => {
  // Callback a http status code, and a payload object
  callback(406, {'name' : 'Sample handler'})
}

// Not found handler 
handlers.notFound = (data, callback) => {
  callback(404)
}

// Router
const router = {
  'sample' : handlers.sample
}

const server = http.createServer((request, response) => {
  const 
    parsedUrl = url.parse(request.url, true)
    path = parsedUrl.pathname,
    trimmedPath = path.replace(/^\/+|\/+$/g,''),
    queryStringObject = parsedUrl.query,
    method = request.method.toLowerCase(),
    headers = request.headers,
    decoder = new StringDecoder.StringDecoder('utf-8')

  let
    buffer = ''

  request.on('data', (data) => {
    buffer += decoder.write(data)
  })

  request.on('end', () => {
    buffer += decoder.end()
    // Chose the handler this request should go to. 
    // If one is not found, use the notFound handler
    const 
      chosenHandler = typeof(router[trimmedPath]) !== 'undefined'
        ? router[trimmedPath]
        : handlers.notFound

    // Construct the data object to send to the handle
    const data = {
      'trimmedPath' : trimmedPath,
      'queryStringObject' : queryStringObject,
      'method' : method,
      'headers' : headers,
      'payload' : buffer
    }

    // Route the request to the handler specified in the router
    chosenHandler(data, (statusCode, payload) => {

      // Use the status code called back by the handler, or default to 200
      statusCode = typeof(statusCode) == 'number'
        ? statusCode
        : 200

      // Use the payload called back by the handler, or default to
      payload = typeof(payload) == 'object'
        ? payload
        : {}

      // Convert the payload to a string
      const 
        payloadString = JSON.stringify(payload)

      // Return the response
      response.writeHead(statusCode)
      response.end(payloadString)

      // Log the request path
      console.log('Returning this response: ', statusCode, payloadString)
    })
  })
})

server.listen(port, () => {
  console.log(`Nodejs running on PORT ${port}`)
})

results matching ""

    No results matching ""