Skip to content

herber/pico

Repository files navigation

pico

Supported by bytes Coverage Status Build Status Build status

A simple & fast http abstraction

Install

$ npm install --save pico-http

Usage

Requests

const pico = require('pico-http');

// Middleware
pico.use((req, res, next) => {
  console.log(req.method + ' ' + req.url + ' on ' + new Date());

  next();
});

// Serve get requests to `/`
pico.get('/', (req, res) => {
  // Set contenttype
  res.contentType('text/html');

  // Send response
  res.send('Hello World');
});

// Serve post requests to `/api`
pico.post('/api', (req, res) => {
  const o = {
    user: 'test'
  };

  res.contentType('application/json');

  res.send(JSON.stringify(o));
});

// Catch every unhandled request
pico.serve('/*', '_', (req, res) => {
  res.status(404);

  res.send('Custom 404');
});

// Listen to port
pico.listen(3000);

API

listen(port)

Listen to http requests on port

port

Type: number

The port that should be used.

use(cb)

Add middleware. Middleware will be executed on every request before specific route handling

cb

Type: function

Will be executed on request

Parameters:
  • req
    Type: object
    Contains request information

  • res
    Type: object
    Use res.send() to send something back to the client

  • next
    Type: function
    Execute next middleware / request handler

serve(route, method, cb)

route

Type: string or regexp

Allowed route

method

Type: string

Http method(eg. GET, POST)

cb

Type: function

Will be executed if route and method match

Parameters:
  • req
    Type: object
    Contains request information

  • res
    Type: object
    Use res.send() to send something back to the client

License

MIT © Tobias Herber

About

A simple & fast http abstraction

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published