Route.get('/', ({ request }) => {
//
})
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
This guide outlines how to use the HTTP Request object to read request data.
The Node.js raw req object can be accessed via request.request .
|
AdonisJs passes the current HTTP request object as part of the HTTP Context which is sent to all route handlers and middleware:
Route.get('/', ({ request }) => {
//
})
In the example above, we use ES6 destructuring to get the request
object from the passed HTTP context object.
The request object offers a number of helpful methods to read the request body.
First, make sure you’ve installed the BodyParser middleware.
If not, follow the steps below.
Fullstack and API only boilerplates come pre-configured with BodyParser middleware. |
Run the BodyParser installation command:
> adonis install @adonisjs/bodyparser
Then, register the provider inside the start/app.js
file:
const providers = [
'@adonisjs/bodyparser/providers/BodyParserProvider'
]
Finally, register the global middleware inside the start/kernel.js
file:
const globalMiddleware = [
'Adonis/Middleware/BodyParser'
]
The following list of methods can be used to read the request body.
Returns an object containing all request data (merges query params and request body data):
const all = request.all()
Returns raw body data as a string:
const raw = request.raw()
If raw data is JSON and Content-type: application/json is set, BodyParser will parse it smartly and return it as part of the post method.
|
Returns an object with only the specified keys:
const data = request.only(['username', 'email', 'age'])
Returns an object with everything except the specified keys (opposite of only):
const data = request.except(['csrf_token', 'submit'])
Get the value of a given key (if it doesn’t exist, return the default
value):
const drink = request.input('drink')
// with default value
const drink = request.input('drink', 'coffee')
Quite often you may want to handle HTML forms that submit an array of data over key/value pairs.
For example, the following form creates multiple users at once:
<form method="POST" action="/users">
<input type="text" name="username[0]" />
<input type="text" name="age[0]" />
<input type="text" name="username[1]" />
<input type="text" name="age[1]" />
</form>
Let’s say we want to get the username and age inside the controller:
const users = request.only(['username', 'age'])
// output
{ username: ['virk', 'nikk'], age: [26, 25] }
The example above can’t save to the database as it’s not in the right format.
Using request.collect
we can format it so it’s ready to save to the database:
const users = request.collect(['username', 'age'])
// output
[{ username: 'virk', age: 26 }, { username: 'nikk', age: 25 }]
// save to db
await User.createMany(users)
You can read headers from the request using one of the following methods.
The header value for a given key (optionally with default value):
var auth = request.header('authorization')
// case-insensitive
var auth = request.header('Authorization')
// with default value
const other = request.header('some-other-header', 'default')
You can read cookies from the request using one of the following methods.
The cookie value for a given key (optionally with default value):
const cartTotal = request.cookie('cart_total')
// with default value
const cartTotal = request.cookie('cart_total', 0)
Returns an object of all cookie data:
const cookies = request.cookies()
The following methods are used to read cookies set on client side.
The raw cookie value for a given key (optionally with default value):
const jsCookie = request.plainCookie('cart_total')
// with default value
const jsCookie = request.plainCookie('cart_total', 0)
Content negotiation is a way for the server and client to decide upon the best response type to be returned from the server.
Web servers don’t only serve web pages – they also have to deal with API responses served as JSON, XML, etc.
Instead of creating separate URLs for each content type, the consumer can ask the server to return the response in a specific format.
To construct the response in a specific format, the server needs to know the requested format first. This can be done using the accepts
method.
Reads the Accept
header to help determine the response format:
const bestFormat = request.accepts(['json', 'html'])
if (bestFormat === 'json') {
return response.json(users)
}
return view.render('users.list', { users })
Language can also be negotiated based upon the Accept-Language
header:
const language = request.language(['en', 'fr'])
Below is a list of all request methods and their example usages.
Returns the full current request url with query strings:
const url = request.originalUrl()
Since AdonisJs allows method spoofing, you can fetch the actual method using the intended
method:
const method = request.intended()
Returns an array of ips from most to the least trusted (removes the default ip address, which can be accessed via the ip
method):
const ips = request.ips()
Returns a list of request subdomains (removes www
from the list):
const subdomains = request.subdomains()
Checks for X-Requested-With
header to determine if the request is ajax or not:
if (request.ajax()) {
// do something
}
Pjax is an evolved way to use Ajax to deliver better user experiences for traditional apps. In the Rails world, it is known as Turbolinks.
This methods looks for the X-PJAX
header to identify if a request is pjax or not:
if (request.pjax()) {
// do something
}
Returns whether the passed set of expressions match the current request URL:
// current request url - posts/1
request.match(['posts/:id']) // returns true
A boolean indicating if the request has a post body (mainly used by the BodyParser to determine whether or not to parse the body):
if (request.hasBody()) {
// do something
}
The is
method returns the best matching content type for the current request.
The check is entirely based upon the content-type
header:
// assuming content-type is `application/json`
request.is(['json', 'html']) // returns - json
request.is(['application/*']) // returns - application/json
HTML forms are only capable of making GET
and POST
requests, which means you cannot utilize the REST conventions of other HTTP methods like PUT
, DELETE
and so on.
AdonisJs makes it simple to bypass the request method by adding a _method
parameter to your query string, executing the correct route for you automatically:
Route.put('users', 'UserController.update')
<form method="POST" action="/users?_method=PUT">
The above example works in the following cases:
The original request method is POST
.
allowMethodSpoofing
is enabled inside the config/app.js
file.
It is also possible to extend the Request
prototype by adding your own methods, known as macros.
Since the code to extend Request need only execute once, you could use providers or Ignitor hooks to do so. Read Extending the Core for more information.
|
const Request = use('Adonis/Src/Request')
Request.macro('cartValue', function () {
return this.cookie('cartValue', 0)
})