Small nodejs http helper.
Installation & Usage
npm i @lbzg/http-help
const http = require('http')
const hh = require('@lbzg/http-help')
const port = 3337
function handler(req, res) {
# assume GET http://this.server/home/sub?slider=27 came in
console.log(hh.getPath(req)) # ['home', 'sub']
console.log(hh.getPath(req, 0)) # 'home'
console.log(hh.getQuery(req)) # {'slider': '27'}
hh.setMime(res, 'text') # sets mime type 'text/plain'
hh.setCors(res, 'http://foo.example') # setCors(res, origin, methods, headers, ttl)
hh.respond(req, res, 200, 'some data') # respond with code 200 and some data
}
http.createServer(handler).listen(port)
Methods
getPath(req, [index = null])
getQuery(req, [stringFormat = false])
getPostBody(req)
setCors(res, [origin = null], [methods = null], [headers = null], [ttl = null])
setMime(res, [mime = 'text'])
respond(req, res, responseCode, responseBody)
Mime types map:
- text > 'text/plain'
- html > 'text/html'
- css > 'text/css'
- js > 'application/javascript'
- json > 'application/json'
- es > 'application/ecmascript'
- form > 'multipart/form-data'
- url-form > 'application/x-www-form-urlencoded'
- stream > 'application/octet-stream'
- jpeg > 'image/jpeg'
- png > 'image/png'