Giter Site home page Giter Site logo

request's Introduction

Request

circleci-image npm-image license-image

Wrapper over Node.js req object to standardize and ease the process of reading data from HTTP requests.

Table of contents

Features

  1. Support for reading plain and signed cookies (only when signed via @poppinss/response)
  2. Handy methods for content negotiation.
  3. Handles inconsistencies between certain headers like referer and referrer.
  4. Reliably reads ip address of proxied requests.
  5. Assigns distributed unique x-request-id to each request.

Usage

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()}`)
})

Config

{
"allowMethodSpoofing": false

Since, standard HTML forms doesn't allow all HTTP verbs like PUT, DELETE and so on. The allowMethodSpoofing allows defining the HTTP method as a query string _method.

When allowMethodSpoofing = true and current request method is POST, then request.method() will give preference to the query string _method property, over the original request method.

"subdomainOffset": 2

Offset indicates the number of values to remove from the end of the URL seperated by ..

For example: For URL indicative.adonisjs.com, the request.subdomains() method will return an array with ['indicative'].

"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 x-real-ip header when used a proxy server. In that case you can define your own getIp method for same.

getIp (request) {
  // I am using nginx as a proxy server and want to trust 'x-real-ip'
  return request.header('x-real-ip')
}
"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.

}

Typescript support

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

API

Following are the autogenerated files via Typedoc

Maintainers

Harminder virk

request's People

Contributors

dependabot-preview[bot] avatar targos avatar thetutlage avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

seanpm2001

request's Issues

Bug in protocol() method

If trustProxy returns false, the protocol() method always returns null.

The reason is that the following line actually will never return a string, because IncomingMessage.url doesn't contain information about the protocol/hostname/port. It only has the path part

const protocol = this.parsedUrl.protocol!

Here's a test case showing the issue:

diff --git a/test/request.spec.ts b/test/request.spec.ts
index cce62c0..4f6b22b 100644
--- a/test/request.spec.ts
+++ b/test/request.spec.ts
@@ -299,6 +299,22 @@ test.group('Request', () => {
     })
   })

+  test('get request protocol without trusting proxy', async (assert) => {
+    const server = createServer((req, res) => {
+      const config = fakeConfig()
+      config.trustProxy = () => false
+      const request = new Request(req, res, config)
+
+        res.writeHead(200, { 'content-type': 'application/json' })
+        res.end(JSON.stringify({ protocol: request.protocol() }))
+      })
+
+      const { body } = await supertest(server).get('/')
+      assert.deepEqual(body, {
+        protocol: 'http',
+      })
+  })
+
   test('get boolean telling request is secure or not', async (assert) => {
     const server = createServer((req, res) => {
       const request = new Request(req, res, fakeConfig())
Request

  โœ– get request protocol without trusting proxy
    Assertion Error: expected { protocol: null } to deeply equal { protocol: 'http' }
    {
      protocol: null => "http"
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.