When making a request to the server, we don't usually care about the internal workings of the request. We just want to send a request, and when the response is received, work with it. Rails makes this task easy because of its UJS driver. The problem is that the driver is tightly bound to the DOM. Which means unless you're working with HTML elements, you won't be able to use the sweet features it provides.
The @unobtrusive/remote-request package is an effort to remove the DOM dependency so that all the goodies can be used without the need to be bound to any HTML element.
$ npm install @unobtrusive/remote-request$ yarn add @unobtrusive/remote-requestTo make a simple request, you create a RemoteRequest object with the given URL and method:
import RemoteRequest from "@unobtrusive/remote-request";
const remoteRequest = new RemoteRequest("https://example.com", "GET");attach the necessary event handlers:
remoteRequest.onSuccess(function({ body }) {
/* ... */
});
remoteRequest.onComplete(function({ status }) {
/* ... */
});and call the send() method on it:
remoteRequest.send();which will start the callback chain to be executed, if there are any callbacks registered.
- Returns a new
RemoteRequestobject - Accepts the
urland themethodusing which the request should be made
- Sends the actual request and starts execution of the callback chain
- Optionally accepts a
body(which can be astring | FormData) to send - Optionally accepts a
responseType(which is the enumResponseType) to expect from the server ResponseTypehas the following values:All: Expects all types of responses; specifically, sets the headerAccept: */*Text: Expects a plain text response; specifically, sets the headerAccept: text/plainHTML: Expects an HTML response; specifically, sets the headerAccept: text/htmlXML: Expects an XML response; specifically, sets the headerAccept: application/xml, text/xmlScript: Expects a JSON response; specifically, sets the headerAccept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascriptJSON: Accepts a JavaScript response; specifically, sets the headerAccept: application/json, text/javascript
- Accepts a
callbackmethod which can either return nothing, or returntrueorfalse - The callback registered via
onStart()is the first to get executed after thesend()method is called and the request is made - If the callback returns
false, the subsequent callbacks are not called; if the callback returnstrueor nothing, the subsequent callbacks are called
- The callback registered via
onSending()gets called after theonStart()callback is finished executing but the request is not yet made - Currently, works the same as
onStart()but that will change when the package is fully released
- The callback registered via
onStop()gets called after either theonStart()callback, or theonSending()callback is finished executing, but only when the callback chain is prematurely cancelled, or normally cancelled- Premature cancellation is when the
onStart()callback returnsfalse; in that case, theonStop()callback will get called immediately after theonStart()callback - Normal cancellation is when the
onSending()callback returnsfalse; in that case, theonStop()callback will get called immediately after theonSending()callback
- Premature cancellation is when the
- The callback registered via
onSend()gets called after theonSending()callback is done executing, and the request has been sent to the server
- The callback registered via
onSuccessgets called after theonSend()callback is done executing; the response have been received, and the server responded with a2xxstatus - The registered callback receives the
RemoteResponseobject which has the following properties:status: number: The status code returned by the server. For e.g.:201reason: string: The reason returned by the server. For e.g.:Createdheaders: (name: string) => string: A function which will return the value of the header, given the header name. For e.g.:headers("Content-Type")might returntext/htmlbody: string | HTMLDocument | Document: The body returned by the URL, parsed accordingly. For e.g.:- When body is HTML (
Content-Type: text/html): Returns theHTMLDocumentobject - When body is XML (
Content-Type: application/xml, text/xml): Returns theDocumentobject, or in some browsers, theXMLDocumentobject - When the body is anything else: Returns the body as a
string
- When body is HTML (
- When the response status is not
2xx, the callback registered viaonFailure()get called instead ofonSuccess() - Rest of the working is the same as
onSuccess()
- The callback registered via
onComplete()are called either after theonSuccess()callback (in case of response2xx), or after theonFailure()callback (in case of response not2xx) - Rest of the working is the same as
onSuccess()oronFailure()
- The callback registered via
onError()gets called after theonSend()callback is done executing, but some network failure happened
- The callback registered via
onTimeout()gets called after theonSend()callback is done executing, but the server took too long to respond and the request timed out
- The callback registered via
onFinish()gets called at the very last after theonComplete(),onError(), oronTimeout()callbacks are executed
By default, there's no timeout, so if the server doesn't respond in time, the request might go on forever. To stop this from happening, before calling the send() method, you can set the timeout as such:
remoteRequest.timeout = 200;The value is accepted in milliseconds.
If the server you're trying to contact requires basic HTTP authentication, call the authorizeWith() method before calling send() to set the credentials:
remoteRequest.authorizeWith("apokolips", "omegalambda7xl9");Cross-origin requests do not send credentials (like cookies) by default. To enable it, set this to true.