Introduction

The @ostro/http/request class in OstroJS gives you an object-oriented method to interact with the current HTTP request being handled by your project, as well as access the input, cookies, and files that were sent along with it.

Interacting With The Request

Accessing The Request

You can access request object controller function to get an instance of the current HTTP request via destructor. The 0stroJS router will send  the incoming request instance automatically:

class UserController extends Controller {
    /**
     * Store a new user.

     */
    store({ request })   {
        let name = request.input('name');
    }
}

You may use request object in router callback instead of controller:


Route.get('/', function ({ request }) {
    let name = request.name
});

Request Path & Method

The @ostro/http/request class and offers a number of methods for analyzing the incoming HTTP request. Below, we'll go through a couple of the more significant ways.

Route Parameters

You should place your route parameters after your other dependents if your controller function also expects input from a route parameter. For instance, suppose your route is specified as follows:

const UserController = require('~/app/http/controllers/userController')

Route.put('/user/:id', [UserController, 'update']);

You may still destruct the httpContext  if you want to. By creating your controller method as follows, you may request and access your id route parameter using params object:

const Controller = require('~/app/http/controllers/controller')

class UserController extends Controller {
    /**
     * Update the specified user.
     *
   
     */
    update({ request, params })    {
        // params.id
    }
}

 

Request Headers

The header method may be used to get a request header from an @ostro/http/request instance. Null will be returned if the header is missing from the request. The header function, on the other hand, takes an optional second parameter, which is returned if the header is missing from the request:

let value = request.header('X-Header-Name');

let value = request.header('X-Header-Name', 'default');

To see if a request has a certain header, use the hasHeader method:

if (request.hasHeader('X-Header-Name')) {
    //
}

The bearerToken method may be used to get a bearer token from the Authorization header for convenience. If there is no such header, an empty string will be returned:

let token = request.bearerToken();

Request IP Address

To get the IP address of the client that made the request to your application, use the ip method:

let ipAddress = request.ip();

Retrieving The Request Method

The HTTP verb for the request will be returned by the method method. The isMethod method may be used to check if an HTTP verb matches a string:

let method = request.method;

if (request.isMethod('post')) {
    //
}

Retrieving The Request URL

The url and fullUrl methods can be used to get the full URL for an incoming request. The url method returns a URL without the query string, whereas the fullUrl method returns a URL that contains the query string:

let url = request.url();

let urlWithQueryString = request.fullUrl();

Call the fullUrlWithQuery function if you want to attach query string data to the current URL. This function combines the current query string with the provided array of query string variables:

request.fullUrlWithQuery({'type' : 'phone'});

Retrieving The Request Path

The path method returns the request's route information. If the inbound request is for http://example.com/foo/bar, the path function will return foo/bar:.

let uri = request.path();

 

Inspecting The Request Path / Route

You may use the is method to check if the incoming request path meets a pattern. When using this approach, you may use the * character as a wildcard:

if (request.is('admin/(.*)')) {
    //
}

You may use the routeIs function to see if an incoming request matches a defined route:

if (request.routeIs('admin.*')) {
    //
}

Content Negotiation

OstroJS offers many ways for checking the requested content types in an incoming request using the Accept header. To begin, the getAcceptableContentTypes function returns an array containing all of the content types that the request accepts:

let contentTypes = request.getAcceptableContentTypes();

The accepts method takes an array of content types and returns true if the request accepts any of the content types. False will be returned otherwise:

if (request.accepts(['text/html', 'application/json'])) {
    // ...
}

The preferences method may be used to identify the content type the request prefers out of an array of content types. Null will be returned if none of the specified content types are accepted by the request:

let preferred = request.prefers(['text/html', 'application/json']);

Because many apps only offer HTML or JSON, you can easily detect if an incoming request expects a JSON answer by using the expectsJson method:

if (request.expectsJson()) {
    // ...
}

Input

Retrieving Input

Using the all method, you may get an array of all of the incoming request's input data. Regardless of whether the incoming request is from an HTML form or an XHR request, this technique can be used:

let input = request.all();

Retrieving A Portion Of The Input Data

The only and unless methods can be used to get a subset of the input data. Both methods use a single array or a dynamic list of parameters as input:

var input = request.only(['username', 'password']);

var input = request.only('username', 'password');

var input = request.except(['credit_card']);

var input = request.except('credit_card');

Retrieving Boolean Input Values

Your application may get "truthy" values that are actually strings when working with HTML components like checkboxes. For instance, "true" or "on." You may obtain these values as booleans using the boolean method for convenience. For 1, "1" true, "true", "on" and "yes," the boolean function returns true. All other options will result in a false result:

let archived = request.boolean('archived');

On the @ostro/http/request instance, you can additionally access user input via dynamic properties. If one of your application's forms has a name field, for example, you may get the value of the field as follows:

let name = request.name;

On the @ostro/http/request instance, you can additionally access user input via dynamic properties. If one of your application's forms has a name field, for example, you may get the value of the field as follows:

Determining If Input Is Present

The has method may be used to see if a value is present on the request. If the value is present on the request, the has method returns true:

if (request.has('name')) {
    //
}

The has method, when given an array, checks to see if all of the provided values are present:

if (request.has(['name', 'email'])) {
    //
}

If a value is present on the request, the whenHas method will execute the provided closure:

request.whenHas('name', function (input) {
    //
})

If the provided value is not present on the request, a second closure can be passed to the whenHas method, which will be executed:

request.whenHas('name', function (input) {
    // The "name" value is present...
}, function () {
    // The "name" value is not present...
});

The possesses If any of the provided values are present, any method returns true:

if (request.hasAny(['name', 'email'])) {
    //
}

You may use the filled method to see if a value is present on the request and isn't empty:

if (request.filled('name')) {
    //
}

If a value is available on the request and it is not empty, the whenFilled function will run the provided closure:

request.whenFilled('name', function (input) {
    //
});

If the provided value is not "filled," a second closure can be passed to the whenFilled function, which will be executed:

request.whenFilled('name', function (input) {
    // The "name" value is filled...
}, function () {
    // The "name" value is not filled...
});

You may use the missing method to see if a certain key is missing from the request:

if (request.missing('name')) {
    //
}

Retrieving Input From The Query String

The query method will only obtain values from the query string, but the input method will retrieve data from the whole request payload (including the query string):

let name = request.query('name');

The second parameter to this function will be returned if the desired query string value data is not present:

let name = request.query('name', 'Helen');

You may use the query method without any parameters to get an associative array of all the query string values:

let query = request.query();

Retrieving An Input Value

You can get all of the user input from your @ostro/http/request instance with just a few basic methods, regardless of whatever HTTP verb was used for the request. The input method may be used to retrieve user input regardless of the HTTP verb:

let name = request.input('name');

As the second argument to the input method, you can give a default value. If the required input value is not present on the request, this value will be returned:

let name = request.input('name', 'Sally');

When working with forms that have array inputs, access the arrays using "dot" notation:V

let name = request.input('products.0.name');

let names = request.input('products.*.name');

To obtain all of the input values as an associative array, call the input method without any arguments:

$input = request.input();

Old Input

OstroJS allows you to carry over input from one request to the next. This functionality is very handy for re-populating forms once validation mistakes have been detected. If you're utilising 0stroJS's built-in validation capabilities, however, you might not need to use these session input flashing methods explicitly since some of OstroJS's built-in validation facilities will call them for you.

Retrieving Cookies From Requests

All cookies produced by the OstroJS framework are encrypted and signed with an authentication code, which means that if the client modifies them, they will be regarded invalid. Use the cookie method on an @ostro/http/request instance to get the cookie value from the request:

let value = request.cookie.get('name');

Input Trimming & Normalization

In your application's global middleware stack, OstroJS provides the AppHttpMiddlewareTrimStrings and AppHttpMiddlewareConvertEmptyStringsToNull middleware by default. The AppHttpKernel class lists this middleware in the global middleware stack. All incoming string fields on the request will be automatically trimmed, and any empty string fields will be converted to null by this middleware. This eliminates the need for you to worry about normalisation issues in your routes and controllers.

Remove the two middleware from your application's middleware stack by deleting them from the $middleware property of your AppHttpKernel class if you want to deactivate this functionality.

Retrieving Old Input

<Invoke the old method on an instance of @ostro/http/request to recover flashed input from a previous request. The old approach will get the session's previously flashed input data:

let username = request.old('username');

A global old helper is also provided by OstroJS. It is more convenient to use the old helper to repopulate the form if you are displaying old information within a Blade template. Null will be returned if no old input exists for the given field:

<input type="text" name="username" value="<%= helpers.old('username') %>">

Flashing Input Then Redirecting

Because you'll frequently want to flash input to the session and then divert to the previous page, you may use the withInput function to quickly link input flashing onto a redirect:

return redirect.to('form').withInput();

return redirect.route('user.create').withInput();

return redirect.to('form').withInput(
    request.except('password')
);

Flashing Input To The Session

The @ostro/http/request class's flash function saves the current session input so that it is available during the user's next request to the application:

request.flash();

You may additionally flash a portion of the request data to the session using the flashOnly and flashExcept methods. These approaches are beneficial for keeping sensitive data out of the session, such as passwords:

request.flashOnly(['username', 'email']);

request.flashExcept('password');

Files

Retrieving Uploaded Files

Using the file method or dynamic properties, you may get uploaded files from an @ostro/http/request instance. The file function returns an instance of the @ostro/http/uploadedFile class, which extends the NodeJS Filesystem class and offers a number of ways to interact with the file:

let file = request.file('photo');

let file = request.photo;

The hasFile method may be used to see if a file is present on the request:

if (request.hasFile('photo')) {
    //
}

Validating Successful Uploads

You may use the isValid function to verify that there were no difficulties uploading the file in addition to verifying if it is present:

if (request.file('photo').isValid()) {
    //
}

 

Storing Uploaded Files

You'll usually utilise one of your preset filesystems to store an uploaded file. The store function of the UploadedFile class moves an uploaded file to one of your discs, which may be a local filesystem or a cloud storage destination like Amazon S3.

The location where the file should be placed relative to the filesystem's specified root directory is accepted by the store method. Because a unique ID will be produced automatically to serve as the filename, this route should not contain a filename.

The name of the disc that should be utilised to store the file is an optional second parameter to the save function. The function will return the file's relative path to the di

path = await request.photo.store('images');

path = await request.photo.store('images', 's3');

If you don't want a filename to be produced automatically, use the storeAs method, which takes as arguments the path, filename, and disc name:

path = await request.photo.storeAs('images', 'filename.jpg');

path = await request.photo.storeAs('images', 'filename.jpg', 's3');

File Paths & Extensions

The UploadedFile class additionally has methods for getting the fully-qualified path and extension of the file. Based on the file's contents, the extension method will attempt to estimate the file's extension. This extension might not be the same as the one provided by the client:

extension = request.photo.extension();

Other File Methods

On UploadedFile instances, there are a number of additional ways accessible. More information about these methods may be found in the class's API documentation.

Configuring Trusted Proxies

While utilising the url helper, you may find that your application does not always create HTTPS URLs when operating behind a load balancer that terminates TLS / SSL certificates. This is usually because your application is receiving traffic on port 80 from your load balancer and is unaware that it should produce secure connections.

To address this, you may use the AppHttpMiddlewareTrustProxies middleware supplied with your OstroJS application, which allows you to rapidly modify the load balancers or proxies that your application should trust. Your trustworthy proxies should be provided as an array in this middleware's $proxies parameter. Configuration isn't the only thing that has to be done.

const Middleware = @ostro\http\middleware\trustProxies
class TrustProxies extends Middleware {
    /**
     * The trusted proxies for this application.
     *
     * @var string|array
     */
    $proxies = [
        '192.168.1.1',
        '192.168.1.2',
    ];
    
}

Configuring Trusted Hosts

Regardless of the value of the HTTP request's Host header, OstroJS will reply to all requests it receives by default. Furthermore, the value of the Host header will be utilised to generate absolute URLs for your application during a web request.

In most cases, you should configure your web server, such as Nginx or Apache, to deliver requests to your application only if the host name matches. If you don't have access to directly configure your web server and need to tell 0stroJS to only reply to specific host names, you may do so by activating the AppHttpMiddlewareTrustHosts middleware for your app.

The $middleware package already contains the TrustHosts middleware.

/**
 * Get the host patterns that should be trusted.
 *
 * @return array
 */
hosts() {
    return [
        'ostro.test',
        this.allSubdomainsOfApplicationUrl(),
    ];
}

The utility function allSubdomainsOfApplicationUrl returns a regular expression that matches all subdomains of your app's app.url configuration setting. When creating an application that uses wildcard subdomains, this helper function provides an easy way to enable all of your application's subdomains.