Request
Module | ejs.web |
Definition | dynamic class Request |
Inheritance | Request ![]() |
Specified | ejscript-2.7 |
Stability | Prototype 8. |
Web request class.
Request objects manage the state and execution of a web request. The HttpServer class creates
instances of Request in response to incoming client requests. The Request object holds the client request state
including the request URL and headers. It provides low-level properties and methods to inspect and control the
request. The Request object is a Stream and by calling the read() and write() methods, request body
content can be read and written.
The response to send back to the client can be defined by setting status and calling setHeaders() and write() to
set the response status, headers and body content respectively.
Properties
Qualifiers | Property | Type | Description |
---|---|---|---|
static const | SecurityTokenName | Security Token for use to help mitigate CSRF security threats. | |
absHome | Uri | Uri for the top-level of the application. This is an absolute Uri that includes scheme and host components. See home to get a relative Uri. | |
get set | async | Boolean | The current async mode.Request does not support sync mode and only supports async mode. Set to true if the stream is in async mode. |
authGroup | String | Authentication group. This property is set to the value of the authentication group header. This field is read-only. | |
authType | String | Authentication method if authorization is being used (basic or digest). Set to null if not using authentication. This field is read-only. 0. | |
authUser | String | Authentication user name. This property is set to the value of the authentication user header. Set to null if not yet defined. This field is read-only. | |
autoFinalizing | Boolean | Control whether auto-finalizing will be used for the request. If autoFinalizing is false, a request must call finalize() to signal the end of write data. If autoFinalize is true, the Request class will automatically call finalize at the conclusion of the request. Applications that wish to keep the request open to the client can suppress auto-finalization by setting autoFinalizing to false or by calling dontAutoFinalize(). This property defaults to true. | |
config | Object | Request configuration. Initially refers to App.config which is filled with the aggregated "ejsrc" content. Middleware may modify to refer to a request local configuration object. | |
contentLength | Number | Get the request content length. This is the length of body data sent by the client with the request. This property is read-only and is set to the length of the request content body in bytes or -1 if not known. Body data is readable by using read() or by using the request object as a stream. | |
contentType | String | The request content type as specified by the "Content-Type" Http request header. This is set to null if not defined. This is the content type of the request body content sent with the request. | |
controller | Controller | Associated Controller object. Set to null if no associated controller. 8. | |
cookies | Object | Cookie headers. Cookies are sent by the client browser via the Set-Cookie Http header. They are typically used used to specify the session state. If sessions are being used, an Ejscript session cookie will be sent to and from the browser with each request. | |
dir | Path | Application web document directory on the local file system. This is set to the directory containing the application. For MVC applications, this is set to the base directory of the application. For non-MVC apps, it is set to the document root directory specified when the HttpServer was instantiated. | |
env | Object | Storage for middleware specific state. Added for JSGI compliance. | |
errorMessage | String | Descriptive error message for the request. This message is defined internally by the Request if a request times out or has a communications error. 8. | |
get | extension | String | The request pathInfo file extension. |
filename | Path | Physical filename for the resource supplying the response content for the request. Virtual requests where the Request uri does not correspond to any physical resource may not define this property. | |
files | Object | Files uploaded as part of the request. For each uploaded file, an instance of UploadFile is created in files. Each element is named by the file upload HTML input element ID in the HTML page form. | |
get | finalized | Boolean | Has the request output been finalized. |
flash | Object | Notification "flash" messages to pass to the next request (only). By convention, the following keys are used. error: Negative errors (Warnings and errors), inform: Informational / postitive feedback (note), warn: Negative feedback (Warnings and errors), *:: Other feedback (reminders, suggestions...). | |
formData | String | The request form parameters as a string. This parameters are www-url decoded from the POST request body data. This is useful to get a stable, sorted string representing the form parameters. | |
headers | Object | Request Http headers. This is an object hash filled with lower-case request headers from the client. If multiple headers of the same key value are defined, their contents will be catenated with a ", " separator as per the HTTP/1.1 specification. Use the header() method if you want to retrieve a single header. Headers defined on the server-side by creating new header entries in headers will preserve case. Use header() if you want to match headers using a mixed case key. e.g. header("Content-Length"). | |
home | Uri | Home URI for the application. This is a relative Uri from the current URI to the the top-most directory level of the application. | |
host | String | Host serving the request. This is initialized to the authorized server hostname (HttpServer.name) if one is configured. Otherwise it will use Http "Host" header value if supplied by the client else the server IP address of the accepting interface. This algorithm attempts to use the most public address available for the server. | |
get | input | Stream | Request content stream. This is equivalent to using "this" as Request objects are streams connected to the input content. Added for JSGI compliance. |
isSecure | Boolean | Flag indicating if the request is using secure communications. This means that TLS/SSL is the underlying protocol scheme. | |
static | jsgi | Object | JSGI specification configuration object. |
limits | Object | Resource limits for the request. The limits have initial default values defined by the owning HttpServer. | |
localAddress | String | Server IP address of the accepting interface. | |
log | Logger | Logger object. Set to App.log. This is configured from the "log" section of the "ejsrc" config file. | |
method | String | Request HTTP method. String containing the Http method (DELETE | GET | POST | PUT | OPTIONS | TRACE). | |
originalMethod | String | Original HTTP request method used by the client. If the method is overridden by including a "-ejs-method-" parameter in a POST request or by defining an X-HTTP-METHOD-OVERRIDE Http header, the original method used by the client is stored in this property and the method property reflects the newly defined value. If method is not overridden, originalMethod will be null. | |
originalUri | Uri | The original request URI supplied by the client. This is the Uri path supplied by the client on the first line of the Http request. It is combined with the HttpServer scheme, host and port components to yield a fully qualified URI. The "uri" property has fields for: scheme, host, port, path, query and reference. The "uri" property is read-only. 0. | |
params | Object | The request form parameters plus other routing parameters. The form parameters are www-url decoded from the POST request body data. See also form. | |
pathInfo | String | Location of the request within the application. This is the portion of the request URL after the scriptName. The pathInfo is originally derrived from uri.path after splitting off the scriptName. Changes to the uri or scriptName properties will not affect the pathInfo property. | |
port | Number | TCP/IP port number for the server of this request. | |
protocol | String | Http request protocol (HTTP/1.0 | HTTP/1.1). | |
query | String | Request query string. This is the portion of the Uri after the "?". Set to null if there is no query. | |
get | queryString | String | Decoded query string (URL query string). Eqivalent to the query property. Added for JSGI compliance. |
reference | String | Request reference string. This is the portion of the Uri after the "#". Set to null if there is no reference. | |
referrer | String | Name of the referring URL. This comes from the request "Referrer" Http header. Set to null if there is no defined referrer. Note: the HTTP header is misspelt as "referer" 0. | |
remoteAddress | String | IP address of the client issuing the request. 8. | |
responded | Boolean | The application has responded in some way. The application has commenced a response by doing some output or setting status. | |
responseHeaders | Object | Http response headers. This is the proposed set of headers to send with the response. The case of header keys is preserved. | |
route | Route | Route used for the request. The route is the matching entry in the route table for the request. The route has properties two properties of particular interest: "name" which is the name of the route and and "type" which classifies the type of request. | |
scheme | String | Http request scheme (http | https). | |
scriptName | String | Script name for the current application serving the request. This is typically the leading Uri portion corresponding to the application, but middleware may modify this to be an arbitrary string representing the application. The script name is often determined by the Router as it parses the request using the routing tables. The scriptName will be set to the empty string if not defined, otherwise is should begin with a "/" character. NOTE: changing script name will not update the home property. | |
get | securityToken | Object | Get a security token to help mitigate CSRF threats. The security token is submitted by forms and requests and can be validated by controllers. The token is stored in session["__ejs-security-token__"]. |
server | HttpServer | Owning server for the request. This is the HttpServer object that created this request. | |
get | serverPort | Number | Listening port number for the server. |
session | Session | Session state object. The session state object can be used to share state between requests. If a session has not already been created, accessing this property automatically creates a new session and sets the Request.sessionID property and a cookie containing a session ID sent to the client with the response. To test if a session has been created, test the sessionID property which will not auto-create a session. Objects are stored in the session state using JSON serialization. | |
sessionID | String | Current session ID. Index into the sessions object. Set to null if no session is defined. | |
status | Number | Set to the (proposed) Http response status code. | |
uri | Uri | The current request URI. This property is read-only and is dynamically computed from the originalUri combined with the current scheme, host, port, scriptName, pathInfo, query and reference property values. The "uri" property has fields for: scheme, host, port, path, query and reference. | |
writeBuffer | ByteArray | Write buffer when capturing output. | |
get | written | Number | The number of bytes written to the client. This is the count of bytes passed to write and buffered, not the actual number of bytes sent to the network connection. |
Request Class Methods
Qualifiers | Method |
---|
Request Instance Methods
Qualifiers | Method |
---|---|
Request(uri: Uri, dir: Path = .) | |
Construct the a Request object. | |
autoFinalize(): Void | |
Finalize the request if autoFinalizing is true. | |
checkSecurityToken() | |
Check the request security token. | |
close(): Void | |
Close the stream.This closes the current request by finalizing all transmission data and sending a "close" event. | |
createSession(timeout: Number = -1): Session | |
Create a session state object. | |
destroySession(): Void | |
Destroy a session. | |
dontAutoFinalize(): Void | |
Stop auto-finalizing the request. | |
error(msg: String): Void | |
Set an error flash notification message. | |
finalize(): Void | |
Signals the end of any and all response data and flushes any buffered write data to the client. | |
finalizeFlash() | |
Save flash messages for the next request and delete old flash messages. | |
flush(dir: Number = expression): Void | |
Flush the stream and underlying streams.Flush request data. | |
header(key: String): String | |
Get a request header by keyword. | |
inform(msg: String): Void | |
Set an informational flash notification message. | |
link(target: Object): Uri | |
Create a URI link. | |
matchContent(formats: Array): String | |
Select the response content type based on the request "Accept" header. | |
notify(key: String, msg: String): Void | |
Set a transient flash notification message. | |
off(name, observer: Function): Void | |
Remove an observer from the stream. | |
on(name, observer: Function): Request | |
Add an observer to the stream for the named events. | |
read(buffer: ByteArray, offset: Number = 0, count: Number = -1): Number | |
Read a data from the stream.If the request is posting a form, i.e. | |
redirect(target: Object, status: Number = expression): Void | |
Redirect the client to a new URL. | |
setCookie(name: String, options: Object) | |
Define a cookie header to send with the response. | |
setHeader(key: String, value: String, overwrite: Boolean = true): Void | |
Convenience routine to set a Http response header in responseHeaders. | |
setHeaders(headers: Object, overwrite: Boolean = true): Void | |
Convenience routine to set multiple Http response headers in responseHeaders. | |
setLimits(limits: Object): Void | |
Update the request resource limits. | |
setLocation(prefix: String, location: Path): Void | |
Convenience routine to define an application at a given Uri prefix and directory location. | |
setStatus(status: Number): Void | |
Convenience routine to set the (proposed) Http response status code. | |
setupFlash() | |
Prepare the flash message area. | |
trace(options: Object): Void | |
Configure request tracing for the request. | |
warn(msg: String): Void | |
Set a warning flash notification. | |
write(data: Array): Number | |
Write data to the stream.Write data to the client. | |
writeError(status: Number, msgs: Array): Void | |
Write an error message back to the user and finalize the request. | |
writeFile(file: Path): Boolean | |
Send a static file back to the client. | |
writeResponse(response: Object): Void | |
Send a response to the client. | |
writeSafe(data: Array): Number | |
Write safely. |
Method Detail
autoFinalize(): Void
- Description
- Finalize the request if autoFinalizing is true. Finalization signals the end of any write data and flushes any buffered write data to the client. This routine is used by frameworks to finalize requests if required.
checkSecurityToken()
- Description
- Check the request security token. If a required security token is defined in the session state, the request must supply the same token with all POST requests. This helps mitigate potential CSRF threats.
- Throws
close(): Void
- Description
- Close the stream.This closes the current request by finalizing all transmission data and sending a "close" event. HttpServer attemps to reuse socket connections so calling close(), may not actually close the socket connection if the reuse limit has not been exceeded (see limits). It is normally not necessary to explicitly call close a request as the web framework will automatically close finalized requests when all input data has fully been read. Calling close on an already closed request is silently ignored.
- Events
close A close event is issued before closing the stream.
- Description
- Create a session state object. The session state object can be used to share state between requests. If a session has not already been created, this call will create a new session and initialize the session property with the new session. It will also set the sessionID property and a cookie containing a session ID that will be sent to the client with the response. Sessions can also be used/created by simply accessing the session property. Objects are stored in the session state using JSON serialization.
- Parameters
timeout: Number Optional session state timeout in seconds. Set to zero for no timeout. After the timeout has expired, the session will be deleted. [default: -1]
destroySession(): Void
- Description
- Destroy a session. This call destroys the session state store that is being used for the current client. If no session exists, this call has no effect. Sessions are created by reading or writing to the session property. 0.
dontAutoFinalize(): Void
- Description
- Stop auto-finalizing the request. This will set autoFinalizing to false. Some web frameworks will "auto-finalize" requests by calling finalize() automatically at the conclusion of the request. Applications that wish to keep the connection open to the client can defeat this auto-finalization by calling dontAutoFinalize().
- Description
- Set an error flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
- Parameters
msg: String Message to store.
finalize(): Void
- Description
- Signals the end of any and all response data and flushes any buffered write data to the client. If the request has already been finalized, this call has no additional effect.
finalizeFlash()
- Description
- Save flash messages for the next request and delete old flash messages. (.
- Description
- Flush the stream and underlying streams.Flush request data. A supplied flush direction argument modifies the effect of this call. If direction is set to Stream.READ, then all read data is discarded. If direction is set to Stream.WRITE, any buffered data is written. Stream.BOTH will cause both directions to be flushed. If the stream is in sync mode, this call will block until all data is written. If the stream is in async mode, it will attempt to write all data but will return immediately. Defaults to Stream.WRITE.Calling flush(Sream.WRITE) or finalize() is required to ensure buffered write data is sent to the client. Flushing the read direction is ignored.
- Description
- Get a request header by keyword. Headers supplied by the remote client are stored in lower-case. Headers defined on the server-side preserve case. This routine supports both by doing a case-insensitive lookup.
- Parameters
key: String Header key value to retrieve. The key match is case insensitive.
- Returns
- The header value.
- Description
- Set an informational flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
- Parameters
msg: String Message to store.
- Description
- Create a URI link. The target parameter may contain partial or complete URI information. The missing parts are supplied using the current request and route tables. The resulting URI is a normalized, server-local URI (begins with "/"). The URI will include any defined scriptName, but will not include scheme, host or port components.
- Parameters
target: Object The URI target. The target parameter can be a URI string or object hash of components. If the target is a string, it is may contain an absolute or relative URI. If the target has an absolute URI path, that path is used unmodified. If the target is a relative URI, it is appended to the current request URI path. The target can also be an object hash of URI components: scheme, host, port, path, reference and query. If these component properties are supplied, these will be combined to create a URI. The URI will be created according to the route URI template. The template may be explicitly specified via a "route" target property. Otherwise, if an "action" property is specified, the route of the same name will be used. If these don't result in a usable route, the "default" route will be used. See the Router for more details. If the target is a string that begins with " @" it will be interpreted as a controller/action pair of the form " @Controller/action". If the "controller/" portion is absent, the current controller is used. If the action component is missing, the "index" action is used. A bare " @" refers to the "index" action of the current controller. Lastly, the target object hash may contain an override "uri" property. If specified, the value of the "uri" property will be returned and all other properties will be ignored.
- Options
scheme String URI scheme portion. host String URI host portion. port Number URI port number. path String URI path portion. reference String URI path reference. Does not include "#". query String URI query parameters. Does not include "?". controller String Controller name if using a Controller-based route. This can also be specified via the action option. action String Action to invoke. This can be a URI string or a Controller action of the form. route String Route name to use for the URI template.
- Returns
- A normalized, server-local Uri object. The returned URI will be an absolute URI.
- Example
Given a current request of http://example.com/samples/demo" and "r" == the current request: r.link("images/splash.png") # "/samples/images/splash.png" r.link("images/splash.png").complete(r.uri) # "http://example.com/samples/images/splash.png" r.link("images/splash.png").relative(r.uri) # "images/splash.png" r.link("http://example.com/index.html") r.link("/path/to/index.html") r.link("\@Controller/checkout") r.link("\@Controller/") r.link("\@checkout") r.link("\@") r.link({action: "checkout") r.link({action: "logout", controller: "Admin") r.link({action: "Admin/logout") r.link({action: "\@Admin/logout") r.link({uri: "http://example.com/checkout"}) r.link({route: "default", action: "\@checkout") r.link({product: "candy", quantity: "10", template: "/cart/{product}/{quantity}}")
- Description
- Select the response content type based on the request "Accept" header. See RFC-2616.
- Parameters
formats: Array Array of server supported mime types.
- Returns
- Formats The selected mime types mime type string Accept: "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png".
- Description
- Set a transient flash notification message. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
- Description
- Remove an observer from the stream.
- Parameters
name Event name previously used with observe. The name may be an array of events. observer: Function Observer function previously used with observe.
- Description
- Add an observer to the stream for the named events.
- Parameters
name: [String|Array] Name of the event to listen for. The name may be an array of events. observer: Function Callback observer function. The function is called with the following signature: function observer(event: String, ...args): Void.
- Events
readable Issued when the stream becomes readable. writable Issued when the stream becomes writable. close Issued when stream is being closed. 8. writable Issued when the connection is writable to accept body data (PUT, POST). close Issued when the request completes. error Issued if the request does not complete or the connection disconnects. An error event is not caused by non-200 status codes, these are regarded as valid return results. Rather, an error event will be issued when the request cannot return a complete, valid Http response to the client. All events are called with the signature: function (event: String, http: Http): Void.
- Description
- Read a data from the stream.If the request is posting a form, i.e. If data is available, the call will return immediately. If no data is available and the stream is in sync mode, the call will block until data is available. If no data is available and the stream is in async mode, the call will not block and will return immediately. In this case a "readable" event will be issued when data is available for reading.the Http ContentType header is set to "application/x-www-form-urlencoded", then the request object will not be created by the HttpServer until all the form data is read and the params collection created and populated with the form data. This permits form data to be processed synchronously without having to use async/observer techniques to respond to readable events. With all other content types, the Request object will be created and run before the incoming client data has been read. To read data in these situations, register an observer function to run when the connection becomes "readable".
- Parameters
buffer: ByteArray Destination byte array for read data. offset: Number Offset in the byte array to place the data. If the offset is -1, then data is appended to the buffer write position which is then updated. If offset is >= 0, the data is read to the offset and the read pointer is set to the offset and the write pointer to one past the end of the data just read. [default: 0] count: Number Read up to this number of bytes. If -1, read as much as the buffer will hold up. If the stream is of fixed and known length (such as a file) and the buffer is of sufficient size or is growable, read the entire stream. If the buffer is of a fixed size, ready only what will fit into the buffer. [default: -1]
- Events
readable Issued when there is new read data available. writable Issued when the stream becomes empty. `.
- Returns
- A count of the bytes actually read. Returns null on EOF or errors.
- Example
request.on("readable", function(event, request) { var data = new byteArray if (read(data)) { print("Got " + data) } else { // End of input, call finalize() when all output has been written request.finalize() } })
- Description
- Redirect the client to a new URL. This call redirects the client's browser to a new target specified by the url. Optionally, a redirection code may be provided. Normally this code is set to be the HTTP code 302 which means a temporary redirect. A 301, permanent redirect code may be explicitly set.
- Parameters
target: Object Uri to redirect the client toward. This can be a relative or absolute string URI or it can be a hash of URI components. For example, the following are valid inputs: ../index.ejs, http://www.example.com/home.html, @list. status: Number Optional HTTP redirection status. [default: expression]
- Description
- Define a cookie header to send with the response. The Path, domain and expires properties can be set to null for default values.
- Options
value Cookie value. path Uri path to which the cookie applies. domain String Domain in which the cookie applies. Must have 2-3 "." and begin with a leading ".". For example: domain: .example.com. expires Date When the cookie expires. secure Boolean Set to true if the cookie only applies for SSL based connections.
- Description
- Convenience routine to set a Http response header in responseHeaders. If a header has already been defined and overwrite is true, the header will be overwritten. NOTE: case is ignored in the header keyword. Access responseHeaders to inspect the proposed response header set.
- Parameters
key: String The header keyword for the request, e.g. "accept". value: String The value to associate with the header, e.g. "yes". overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator. [default: true]
- Description
- Convenience routine to set multiple Http response headers in responseHeaders. Access responseHeaders to inspect the proposed response header set.
- Description
- Convenience routine to define an application at a given Uri prefix and directory location. This is typically called from routing tables. This sets the pathInfo scriptName and dir properties.
- Parameters
prefix: String The leading Uri prefix for the application. This prefix is removed from the pathInfo and the scriptName property is set to the prefix. The script name should begin with "/". location: Path Path to where the application home directory is. This sets the dir property to the location argument.
- Description
- Convenience routine to set the (proposed) Http response status code. This is equivalent to assigning to the status property.
setupFlash()
- Description
- Prepare the flash message area. This copies flash messages from the session state store into the flash store.
- Description
- Configure request tracing for the request. The default is to trace the first line of requests and responses at level 2 and to trace headers at level 3. The options argument contains optional properties. These may contain an object hash which describes the following fields:.
- Parameters
options: Object Set of trace options with properties for: The connection property specifies that new connections should be traced. The error property specifies that new connections should be traced. The info property specifies that new connections should be traced. The rxFirst property specifies that the first line of the request should be traced. The rxHeaders property specifies that the headers (including first line) of the request should be traced. The rxBody property specifies that the body content of the request should be traced. The txFirst property specifies that the first line of the response should be traced. The txHeaders property specifies that the headers (including first line) of the response should be traced. The txBody property specifies that the body content of the request should be traced. The complete property specifies that the body content of the request should be traced. The size property specifies a maximum body size in bytes that will be traced. Content beyond this limit will not be traced.
- Example
trace({ "rxHeaders": 3, "rxBody": 4, size: 1000000 })
- Description
- Set a warning flash notification. Flash messages persist for only one request and are a convenient way to pass state information or feedback messages to the next request. To use flash messages, setupFlash() and finalizeFlash() must be called before and after the request is processed. HttpServer.process will call setupFlash and finalizeFlash automatically.
- Parameters
msg: String Message to store.
- Description
- Write data to the stream.Write data to the client. If the stream can accept all the write data, the call returns immediately with the number of bytes written. If writing more data than the stream can absorb in sync mode, the call will block until the data is written. If writing more data than the stream can absorb in async mode, the call will not block and will buffer the data and return immediately. Some streams will require a flush() call to actually send the data. A "writable" event will be issued when the stream can again absorb more data.This will buffer the written data until either flush() or finalize() is called. 0
- Parameters
data: Array Data to write.
- Events
readable Issued when data is written and a consumer can read without blocking. writable Issued when the stream becomes empty and it is ready to be written to.
- Returns
- A count of the bytes actually written.
- Throws
- IOError: if there is an I/O error.
- Description
- Send a static file back to the client. This is a high performance way to send static content to the client by using the "sendConnector". To be effective, this call must be invoked prior to sending any data or headers to the client, otherwise it will be ignored and the slower "netConnector" will be used instead.
- Parameters
file: Path Path to the file to send back to the client.
- Returns
- True if the Send connector can successfully be used. 8.
- Description
- Send a response to the client. This can be used instead of setting status and calling setHeaders() and write(). The response argument is an object hash containing status, headers and body properties. The respond method replaces previously defined status and headers.
- Options
status Numeric Http status code (e.g. 200 for a successful response). header Object hash of Http headers. body Body content.
- Description
- Write safely. Write HTML escaped data back to the client.
- Parameters
data: Array Objects to HTML encode and write back to the client. 0.