Wrapper over Node.js req object to standardize and ease the process of reading data from HTTP requests.
- Support for reading plain and signed cookies (only when signed via @poppinss/response)
- Handy methods for content negotiation.
- Handles inconsistencies between certain headers like
referer
andreferrer
. - Reliably reads
ip address
of proxied requests. - Assigns distributed unique
x-request-id
to each request.
Install the package from npm as follows:
npm i @poppinss/request
# yarn
yarn add @poppinss/request
and then use it as follows
import { Request, RequestConfigContract } from '@poppinss/request'
import { createServer } from 'http'
const config: RequestConfigContract = {
allowMethodSpoofing: false,
subdomainOffset: 2,
trustProxy: require('proxy-addr').compile('loopback'),
}
createServer((req, res) => {
const request = new Request(req, res, config)
res.end(`${request.id()} ${request.url()}`)
})
{ |
|
"allowMethodSpoofing": false |
Since, standard HTML forms doesn't allow all HTTP verbs like
When |
"subdomainOffset": 2 |
Offset indicates the number of values to remove from the end of the URL seperated by
For example: For URL |
"trustProxy" |
A method that allows you to selectively trust the proxy servers. Make sure to read proxy-addr docs. |
"getIp" |
Optionally define a method to determine the user Ip adress. The method is helpful, when you want to rely on a different property to find the user ip address.
For example: Nginx set
|
"secret" |
Optional Define a secret to unsign and read cookies. Make sure you have used the same secret to sign the cookie via @poppinss/response package. |
} |
The module is written in Typescript and exports following classes, types and interfaces.
import { Request, RequestContract, RequestConfigContract} from '@poppinss/request'
RequestContract is the interface that Request
class adheres too. Since, you cannot extend concrete implementations in Typescript, you may need the interface to have a lossely typed flow.
Request.macro('cartValue', function () {
return Number(this.cookie('cart')) || 0
})
then, you need to add cartValue
to the interface
import { RequestContract as BaseContract } from '@poppinss/request'
interface RequestContract extends BaseContract {
cartValue (): number
}
const request = new Request(req, res, config) as unknown as RequestContract
Following are the autogenerated files via Typedoc