Documentation
    Preparing search index...

    HTTP Request class exposes the interface to consistently read values related to a given HTTP request. The class is wrapper over IncomingMessage and has extended API.

    You can access the original IncomingMessage using request.request property.

    Hierarchy

    • default
      • Request
    Index

    Constructors

    • Creates a new Request instance wrapping the native Node.js HTTP request

      Parameters

      • request: IncomingMessage

        Native Node.js incoming message instance

      • response: ServerResponse

        Native Node.js server response instance

      • encryption: Encryption

        Encryption module for cookie and URL signing

      • config: RequestConfig

        Request configuration options

      • qsParser: Qs

        Query string parser instance

      Returns Request

    Properties

    parsedUrl: { pathname: string; query: string; shouldDecodeParam: boolean }

    Parsed URL with query string stored as a string and decode flag

    Type Declaration

    • pathname: string

      The pathname portion of the URL

    • query: string

      The query string portion of the URL

    • shouldDecodeParam: boolean

      Flag indicating whether parameters should be decoded

    HTTP context reference - creates a circular reference when set by the context

    request: IncomingMessage

    Native Node.js incoming message instance

    response: ServerResponse

    Native Node.js server response instance

    Methods

    • Returns the request id from the x-request-id header. The header is untouched, if it already exists.

      Returns undefined | string

      The request ID or undefined if not found/generated

    • Set initial request body. A copy of the input will be maintained as the original request body. Since the request body and query string is subject to mutations, we keep one original reference to flash old data (whenever required).

      This method is supposed to be invoked by the body parser and must be called only once. For further mutations make use of updateBody method.

      Parameters

      • body: Record<string, any>

        Parsed request body data

      Returns void

    • Update the request body with new data object. The all property will be re-computed by merging the query string and request body.

      Parameters

      • body: Record<string, any>

        New request body data to set

      Returns void

    • Update the request raw body. Bodyparser sets this when unable to parse the request body or when request is multipart/form-data.

      Parameters

      • rawBody: string

        Raw request body as string

      Returns void

    • Update the query string with the new data object. The all property will be re-computed by merging the query and the request body.

      Parameters

      • data: Record<string, any>

        New query string data to set

      Returns void

    • Returns route params

      Returns Record<string, any>

      Object containing route parameters

    • Returns the query string object by reference

      Returns Record<string, any>

      Object containing parsed query string parameters

    • Returns reference to the request body

      Returns Record<string, any>

      Object containing parsed request body

    • Returns reference to the merged copy of request body and query string

      Returns Record<string, any>

      Object containing merged request body and query parameters

    • Returns reference to the merged copy of original request query string and body

      Returns Record<string, any>

      Object containing original merged request data

    • Returns the request raw body (if exists), or returns null.

      Ideally you must be dealing with the parsed body accessed using [[input]], [[all]] or [[post]] methods. The raw body is always a string.

      Returns null | string

      Raw request body as string or null if not set

    • Returns value for a given key from the request body or query string. The defaultValue is used when original value is undefined.

      Parameters

      • key: string

        Key to lookup in request data

      • OptionaldefaultValue: any

        Default value when key is not found

      Returns any

      Value from request data or default value

      request.input('username')

      // with default value
      request.input('username', 'virk')
    • Returns value for a given key from route params

      Parameters

      • key: string

        Parameter key to lookup

      • OptionaldefaultValue: any

        Default value when parameter is not found

      Returns any

      Value from route parameters or default value

      request.param('id')

      // with default value
      request.param('id', 1)
    • Get everything from the request body except the given keys.

      Parameters

      • keys: string[]

        Array of keys to exclude from the result

      Returns Record<string, any>

      Object with all request data except specified keys

      request.except(['_csrf'])
      
    • Get value for specified keys.

      Type Parameters

      • T extends string

      Parameters

      • keys: T[]

        Array of keys to include in the result

      Returns { [K in string]: any }

      Object with only the specified keys from request data

      request.only(['username', 'age'])
      
    • Returns the HTTP request method. This is the original request method. For spoofed request method, make use of [[method]].

      Returns string

      Original HTTP method from the request

      request.intended()
      
    • Returns the request HTTP method by taking method spoofing into account.

      Method spoofing works when all of the following are true.

      1. app.http.allowMethodSpoofing config value is true.
      2. request query string has _method.
      3. The [[intended]] request method is POST.

      Returns string

      HTTP method (potentially spoofed)

      request.method()
      
    • Returns a copy of headers as an object

      Returns IncomingHttpHeaders

      Object containing all HTTP headers

    • Returns value for a given header key. The default value is used when original value is undefined.

      Parameters

      • key: string

        Header name to lookup

      • OptionaldefaultValue: any

        Default value when header is not found

      Returns undefined | string

      Header value or default value if not found

    • Returns the ip address of the user. This method is optimize to fetch ip address even when running your AdonisJs app behind a proxy.

      You can also define your own custom function to compute the ip address by defining app.http.getIp as a function inside the config file.

      {
      http: {
      getIp (request) {
      // I am using nginx as a proxy server and want to trust 'x-real-ip'
      return request.header('x-real-ip')
      }
      }
      }

      You can control the behavior of trusting the proxy values by defining it inside the config/app.js file.

      {
      http: {
      trustProxy: '127.0.0.1'
      }
      }

      The value of trustProxy is passed directly to proxy-addr

      Returns string

      Client IP address

    • Returns an array of ip addresses from most to least trusted one. This method is optimize to fetch ip address even when running your AdonisJs app behind a proxy.

      You can control the behavior of trusting the proxy values by defining it inside the config/app.js file.

      {
      http: {
      trustProxy: '127.0.0.1'
      }
      }

      The value of trustProxy is passed directly to proxy-addr

      Returns string[]

      Array of IP addresses from most to least trusted

    • Returns the request protocol by checking for the URL protocol or X-Forwarded-Proto header.

      If the trust is evaluated to false, then URL protocol is returned, otherwise X-Forwarded-Proto header is used (if exists).

      You can control the behavior of trusting the proxy values by defining it inside the config/app.js file.

      {
      http: {
      trustProxy: '127.0.0.1'
      }
      }

      The value of trustProxy is passed directly to proxy-addr

      Returns string

      Request protocol ('http' or 'https')

    • Returns a boolean telling if request is served over https or not. Check [[protocol]] method to know how protocol is fetched.

      Returns boolean

      True if request is served over HTTPS

    • Returns the request host. If proxy headers are trusted, then X-Forwarded-Host is given priority over the Host header.

      You can control the behavior of trusting the proxy values by defining it inside the config/app.js file.

      {
      http: {
      trustProxy: '127.0.0.1'
      }
      }

      The value of trustProxy is passed directly to proxy-addr

      Returns null | string

      Request host or null if not found

    • Returns the request hostname. If proxy headers are trusted, then X-Forwarded-Host is given priority over the Host header.

      You can control the behavior of trusting the proxy values by defining it inside the config/app.js file.

      {
      http: {
      trustProxy: '127.0.0.1'
      }
      }

      The value of trustProxy is passed directly to proxy-addr

      Returns null | string

      Request hostname (without port) or null if not found

    • Returns an array of subdomains for the given host. An empty array is returned if [[hostname]] is null or is an IP address.

      Also www is not considered as a subdomain

      Returns string[]

      Array of subdomains (excluding www)

    • Returns a boolean telling, if request X-Requested-With === 'xmlhttprequest' or not.

      Returns boolean

      True if request is an AJAX request

    • Returns a boolean telling, if request has X-Pjax header set or not

      Returns boolean

      True if request is a PJAX request

    • Returns the request relative URL.

      Parameters

      • OptionalincludeQueryString: boolean

        Whether to include query string in the URL

      Returns string

      Request pathname, optionally with query string

      request.url()

      // include query string
      request.url(true)
    • Returns the complete HTTP url by combining [[protocol]]://[[hostname]]/[[url]]

      Parameters

      • OptionalincludeQueryString: boolean

        Whether to include query string in the URL

      Returns string

      Complete URL including protocol and host

      request.completeUrl()

      // include query string
      request.completeUrl(true)
    • Find if the current HTTP request is for the given route or the routes

      Parameters

      • routeIdentifier: string | string[]

        Route name, pattern, or handler reference to match

      Returns boolean

      True if the request matches any of the given route identifiers

    • Returns the best matching content type of the request by matching against the given types.

      The content type is picked from the content-type header and request must have body.

      The method response highly depends upon the types array values. Described below:

      Type(s) Return value
      ['json'] json
      ['application/*'] application/json
      ['vnd+json'] application/json

      Parameters

      • types: string[]

        Array of content types to match against

      Returns null | string

      Best matching content type or null if no match

      const bodyType = request.is(['json', 'xml'])

      if (bodyType === 'json') {
      // process JSON
      }

      if (bodyType === 'xml') {
      // process XML
      }
    • Returns the best type using Accept header and by matching it against the given types.

      If nothing is matched, then null will be returned

      Make sure to check accepts package docs too.

      Type Parameters

      • T extends string

      Parameters

      • types: T[]

        Array of types to match against Accept header

      Returns null | T

      Best matching accept type or null if no match

      switch (request.accepts(['json', 'html'])) {
      case 'json':
      return response.json(user)
      case 'html':
      return view.render('user', { user })
      default:
      // decide yourself
      }
    • Return the types that the request accepts, in the order of the client's preference (most preferred first).

      Make sure to check accepts package docs too.

      Returns string[]

      Array of accepted types in preference order

    • Returns the best language using Accept-language header and by matching it against the given languages.

      If nothing is matched, then null will be returned

      Make sure to check accepts package docs too.

      Type Parameters

      • T extends string

      Parameters

      • languages: T[]

        Array of languages to match against Accept-Language header

      Returns null | T

      Best matching language or null if no match

      switch (request.language(['fr', 'de'])) {
      case 'fr':
      return view.render('about', { lang: 'fr' })
      case 'de':
      return view.render('about', { lang: 'de' })
      default:
      return view.render('about', { lang: 'en' })
      }
    • Return the languages that the request accepts, in the order of the client's preference (most preferred first).

      Make sure to check accepts package docs too.

      Returns string[]

      Array of accepted languages in preference order

    • Returns the best charset using Accept-charset header and by matching it against the given charsets.

      If nothing is matched, then null will be returned

      Make sure to check accepts package docs too.

      Type Parameters

      • T extends string

      Parameters

      • charsets: T[]

        Array of charsets to match against Accept-Charset header

      Returns null | T

      Best matching charset or null if no match

      switch (request.charset(['utf-8', 'ISO-8859-1'])) {
      case 'utf-8':
      // make utf-8 friendly response
      case 'ISO-8859-1':
      // make ISO-8859-1 friendly response
      }
    • Return the charsets that the request accepts, in the order of the client's preference (most preferred first).

      Make sure to check accepts package docs too.

      Returns string[]

      Array of accepted charsets in preference order

    • Returns the best encoding using Accept-encoding header and by matching it against the given encodings.

      If nothing is matched, then null will be returned

      Make sure to check accepts package docs too.

      Type Parameters

      • T extends string

      Parameters

      • encodings: T[]

        Array of encodings to match against Accept-Encoding header

      Returns null | T

      Best matching encoding or null if no match

    • Return the encodings that the request accepts, in the order of the client's preference (most preferred first).

      Make sure to check accepts package docs too.

      Returns string[]

      Array of accepted encodings in preference order

    • Returns a boolean telling if request has body

      Returns boolean

      True if request contains a body

    • Returns a boolean telling if the new response etag evaluates same as the request header if-none-match. In case of true, the server must return 304 response, telling the browser to use the client cache.

      You won't have to deal with this method directly, since AdonisJs will handle this for you when http.etag = true inside config/app.js file.

      However, this is how you can use it manually.

      const responseBody = view.render('some-view')

      // sets the HTTP etag header for response
      response.setEtag(responseBody)

      if (request.fresh()) {
      response.sendStatus(304)
      } else {
      response.send(responseBody)
      }

      Returns boolean

      True if client cache is fresh (should return 304)

    • Opposite of [[fresh]]

      Returns boolean

      True if client cache is stale (should send new response)

    • Returns all parsed and signed cookies. Signed cookies ensures that their value isn't tampered.

      Returns { [key: string]: any }

      Object containing all parsed cookies

    • Returns value for a given key from signed cookies. Optional defaultValue is returned when actual value is undefined.

      Parameters

      • key: string

        Cookie name to lookup

      • OptionaldefaultValue: string

        Default value when cookie is not found

      Returns any

      Cookie value or default value if not found

    • Returns value for a given key from encrypted cookies. Optional defaultValue is returned when actual value is undefined.

      Parameters

      • key: string

        Cookie name to lookup

      • OptionaldefaultValue: string

        Default value when cookie is not found

      Returns any

      Decrypted cookie value or default value if not found

    • Returns value for a given key from unsigned cookies. Optional defaultValue is returned when actual value is undefined.

      Parameters

      • key: string

        Cookie name to lookup

      • Optionaloptions: { defaultValue?: string; encoded?: boolean }

        Options object with defaultValue and encoded flag

      Returns any

      Plain cookie value or default value if not found

    • Returns value for a given key from unsigned cookies. Optional defaultValue is returned when actual value is undefined.

      Parameters

      • key: string

        Cookie name to lookup

      • OptionaldefaultValue: string
      • Optionalencoded: boolean

      Returns any

      Plain cookie value or default value if not found

    • Returns a boolean telling if a signed url has a valid signature or not.

      Parameters

      • Optionalpurpose: string

        Optional purpose for signature verification

      Returns boolean

      True if the signed URL has a valid signature

    • Serializes request to JSON format

      Returns {
          id: undefined | string;
          url: string;
          query: string;
          body: Record<string, any>;
          params: Record<string, any>;
          headers: IncomingHttpHeaders;
          method: string;
          protocol: string;
          cookies: { [key: string]: any };
          hostname: null | string;
          ip: string;
          subdomains: Record<string, any>;
      }

      Object representation of the request

    • toJSON copy of the request

      Returns {
          id: undefined | string;
          url: string;
          query: string;
          body: Record<string, any>;
          params: Record<string, any>;
          headers: IncomingHttpHeaders;
          method: string;
          protocol: string;
          cookies: { [key: string]: any };
          hostname: null | string;
          ip: string;
          subdomains: Record<string, any>;
      }

      JSON representation of the request