Sails is built on Express, and uses Node's HTTP server conventions. Because of this, you can access all of the Node and Express methods and properties on the req
object whereever it is accessible (i.e. in your controllers, policies, and custom responses.)
A nice side effect of this compatibility is that, in many cases, you can paste existing Node.js code into a Sails app and it will work. And since Sails implements a transport-agnostic request interpreter, the code in your Sails app is WebSocket-compatible as well.
Sails adds a few methods and properties of its own to the req
object, like req.wantsJSON
and req.params.all()
. These features are syntactic sugar on top of the underlying implementation, and also support both HTTP and WebSockets.
The Supported Features section includes a chart summarizes which methods and properties are available for each transport.
This property is used to check whether JSON is in the list of acceptable Content-Type
s provided by the user-agent in the HTTP request header.
convertToXML = function(someRecord){
// pretend there is code in here
// that parses JSON into XML
}
Users.findOne({name:'Walter'}).exec(function foundHim(err,record){
var myRecord = record;
});
// Check to see if the client can handle JSON. If not, give them XML.
if (req.wantsJSON)
res.send(myRecord)
else
res.send(convertToXML(myRecord));
This method searches the http request body , header, and query string for a parameter with name equal to the supplied parameter.
var myParam = req.param('blueStuff');
// myParam would contain the value of 'blueStuff'
This is nice. Sails makes it nicer by making ALL params available through req.params.all(). See this method somewhere below.
This is an object containing information about files uploaded through the Express bodyParser.
If a file field was named "image" and as a value contained a sucessfully uploaded file, req.files.image would contain the following File object:
{ size: 74643,
path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
name: 'edge.png',
type: 'image/png',
hash: false,
lastModifiedDate: Thu Aug 09 2012 20:07:51 GMT-0700 (PDT),
_writeStream:
{ path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
fd: 13,
writable: false,
flags: 'w',
encoding: 'binary',
mode: 438,
bytesWritten: 74643,
busy: false,
_queue: [],
_open: [Function],
drainable: true },
length: [Getter],
filename: [Getter],
mime: [Getter] }
This is an object containing information about the route by which request traveled.
console.log(req.route);
/*
{ path: '/user/:id?',
method: 'get',
callbacks: [ [Function] ],
keys: [ { name: 'id', optional: true } ],
regexp: /^\/user(?:\/([^\/]+?))?\/?$/i,
params: [ id: '12' ] }
*/
This contains the unsigned cookies sent by the user-agent.
// Assuming the browser sends a cookie named 'Yummy'
console.log(req.cookies.name);
// "Yummy"
You should never have to use this method. While it can be overridden, by default Sails uses the express cookieParser middleware which blanks req.cookies
This contains the signed cookies sent by the user-agent.
// Assuming the browser sends a SIGNED cookie named 'Yummy'
console.log(req.signedCookies.user);
// "Yummy"
You should never have to use this method. While it can be overridden, by default Sails uses the express cookieParser middleware which blanks req.signedCookies
Get the value of a field within the http request header with name equal to the supplied parameter.
// assuming a header field named 'myField' with value 'cat'
console.log(req.get('myField'));
// cat
Checks if the supplied argument is found in the list of acceptable Content-Types specified by the user-agent who sent the request.
// Accept: text/html
req.accepts('html');
// "html"
// Accept: text/*, application/json
req.accepts('html');
// "html"
req.accepts('text/html');
// "text/html"
req.accepts('json, text');
// "json"
req.accepts('application/json');
// "application/json"
// Accept: text/*, application/json
req.accepts('image/png');
req.accepts('png');
// undefined
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
req.accepts('html, json');
// "json"
Return an array of Accepted media types ordered from highest quality to lowest.
console.log(req.accepted);
/*
[ { value: 'application/json',
quality: 1,
type: 'application',
subtype: 'json' },
{ value: 'text/html',
quality: 0.5,
type: 'text',
subtype: 'html' } ]
*/
Checks if the incoming request contains the "Content-Type" header field, and it matches the given mime type.
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// true
// When Content-Type is application/json
req.is('json');
req.is('application/json');
req.is('application/*');
// true
req.is('html');
// false
Get the client's IP address.
This property contains the IP address of the client initiating the request.
console.log(req.ip);
// "127.0.0.1"
When "trust proxy" is true
, parse the "X-Forwarded-For" ip address list and return an array, otherwise an empty array is returned. For example if the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"]
where "proxy2" is the furthest down-stream.
Returns the request URL pathname.
// example.com/users?sort=desc
console.log(req.path);
// '/users'
Returns the hostname from the "Host" header field (without the port number)
// Host: "example.com:3000"
console.log(req.host);
// "example.com"
Check if the request is fresh - aka Last-Modified and/or the ETag still match, indicating that the resource is "fresh".
console.log(req.fresh)
// true
Check if the request was issued with the "X-Requested-With" header field set to "XMLHttpRequest" (AJAX)
console.log(req.xhr);
// true
This property contains the transport protocol of the request
console.log(req.protocol)
// "http"
Is a TLS connection established?
'https' == req.protocol;
This property is an array that contains all of the subdomains found in the URL
This property contains the 'method' specified in the http request?
GET,POST,PUT,etc
This property contains the original URL
This property is an array that contains the acceptable languages specified by the user agent in the http request.
This often isnt specified by the user agent
This property is an array that contains the acceptable charsets specified by the user agent in the http request.
This often isnt specified by the user agent
This method checks to see if the paramater supplied is found in req.acceptedCharsets.
Yo dawg. I heard you like to iterate.
This method checks to see if the paramater supplied is found in req.acceptedLanguages.
Returns whether or not the request was delivered via socket.io
// This would allow you to do different things with the same controller action
// based on whether the request is coming via sockets or http
if (req.isSocket){
// You're a socket. Do socket stuff.
} else {
// Just an http request? Have some HTML.
res.view();
}
This gathers all parameters found in both http AND sockets requests. It returns the value of the parameter supplied, assuming it exists.
if (req.isSocket){
// Assuming you passed a parameter called 'socketParam' with value 'true' via socket.get()
console.log(req.params.all('socketParam'));
// true
} else {
// Assuming you passed a parameter called 'httpParam' with value 'true' in the query string
console.log(req.params.all('httpParam'));
// true
res.view();
}
// They Both Work !
This is used to obtain the id of the Socket.IO socket.
// You might use this if you ever had to debug connectivity issues with Socket.IO
console.log(socket.id);
//
This is generated by the socket.io server on first connection and kept for the duration of the session.
You probably wont use it.
This is a low level Socket.IO method. Check their docs here.
Sails provides its own methods for this and we think they are better. Learn about them right here.
This is a low level socket.io method. Check their docs here.
This is a low level socket.io method. Check their docs here.
Check the value of this property to see which transport mechanism was used by socket.io for the request
This property contains the original URL string requested by the user-agent.