In-depth introduction to dojo/Request

Source: Internet
Author: User
Difficulty: Moderate dojo version: 1.7 Author: Bryan Forbes Translator: Oliver (zhuxw1984@gmail.com) Original article: http://www.sitepen.com/blog/2012/08/21/introducing-dojorequest/


As dojo stride towards 2.0, we have begun to provide developers with tools to maintain efficient productivity in any JavaScript environment. This means that the APIS we created must be consistent in all environments. From this perspective, APIs in one field are always omitted, that is, the IO function of dojo. We have provided developers with a method (Dojo. xhr *, dojo. io. IFRAME, dojo. io. script), but some people do not like the inconsistency (such as Dojo. xhrget and dojo. io. script. get, and so on ). In addition, we have never provided a set of server-side implementations. Even if we provide it, it must be another set of different modules and APIs, and we need to remember more.
With the release of dojo1.8, we launched the dojo/requestapi. This API is consistent across all browsers, request methods, and even JavaScript environments:

require(["dojo/request"], function(request){    var promise = request(url, options);    promise.then(        function(data){        },        function(error){        }    );    promise.response.then(        function(response){        },        function(error){        }    );    request.get(url, options).then(...);    request.post(url, options).then(...);    request.put(url, options).then(...);    request.del(url, options).then(...);});

The signature of the dojo/Request function (and all the functions that initiate requests under this module) contains a URL and an option object. Parameters related to this request can be configured in this option object. It is usually very simple to use dojo/request. You only need to pass a string. The option parameter can be omitted. Let's take a look at the common configuration parameters in the option object:

  • Method: The HTTP Method Used for this request (the default value is get, and this parameter is ignored by dojo/Request/script)
  • Query: A string like Key = value, or an object like {key: 'value'}, containing all query parameters
  • Data: a string or object that is serialized into a string by the dojo/io-query.objectToQuery, indicating the data to be sent (this parameter is ignored by get and delet requests)
  • Handleas: indicates how to handle the server response string. The default value is "text". Other possible values include 'json', 'javascript ', and 'xml'
  • Headers: objects in the form of {'header-name': 'value'}, including various header attributes required by the request
  • Timeout: the number of milliseconds to wait to calculate the timeout integer. Once the timeout period expires, the request will be canceled and the promise returned by "reject (reject)" will be canceled.
API consistency also includes return values: All the dojo/request methods return a "Promise" object, which will eventually provide response data. If a response content parser (via handleas parameter) is specified when a request is initiated, the promise object will provide the parsing result of the content parser, otherwise, it will directly return the text of the response body.
The promise object returned by the dojo/request has an additional property not available to the common promise: response. This attribute is also a promise, which provides an object to describe the response in more detail:
  • URL: The final URL of the request (with the query string added)
  • Options: Request-related parameters
  • Text: String representation of data in the response
  • Data: The data returned after the response is processed (if the handles parameter specifies a valid Parsing Method)
  • Getheader (headername): A function used to obtain Request Header parameters. If a provider does not provide header information, this function returns NULL.

Provider (the module that can provide a certain method of request processing) is behind the scenes. dojo/request initiates a request through provider. A suitable default provider is selected for each platform: the browser uses dojo/Request/xhr, and node. js uses dojo/Request/node. It should be noted that the new browsers (ie9 +, ff3.5 +, chrome7 +, and safari4 +) will use the xmlhttprequest2 event instead of the onreadystatechange of XMLHttpRequest, it will only be used in older browsers. In addition, the provider of node. js directly uses the HTTP and HTTPS modules, which means that no intermediate layer is deployed on the server to accept XMLHttpRequest requests.
If you want to use a non-default provider, such as a provider for a JSON-P, you have three options: directly using a non-default provider; configuring it as the default provider; or configuring the registration information for the request.
Since all providers follow the dojo/request API, non-default providers can be used directly. The Architecture Design of dojo/request is similar to that of dojo/store. This means that if you only have some JSON-P services, you can directly use the dojo/Request/script without changing the basic API signature. Compared with the other two methods, this non-default provider method is less flexible, but it is indeed a completely effective method.
Another way to use a non-default provider is to configure it as the default provider. If we know that our application only uses this provider, It is very helpful. Configuring the default provider is actually very simple, that is, setting the module ID of the provider to the requestprovider attribute of dojoconfig:
<script>    var dojoConfig = {        requestProvider: "dojo/request/script"    };</script><script src="path/to/dojo/dojo.js"></script>

Requestprovider can also be set through data-Dojo-config, just like other configuration parameters. In addition, any function that follows the dojo/request API can be used as the default provider. Of course, we can also develop a custom module to package dojo/Request/xhr, with additional header information (for example, used for identity authentication), we can use it as a custom provider for our applications. In the test phase, we can also use a special provider to simulate the response sent from the server, so that we can verify whether our application is sending the correct request.
Although configuring a non-default provider as a default can provide us with more flexibility than simply using a non-default provider, it still cannot be done through only one API (Dojo/request) you can automatically use different providers based on Preset conditions. Assume that our application has some data services, one of which requires a set of header information for authentication, and the other needs a completely different set of header information. Or one needs a JSON-P and the other needs XMLHttpRequest. In this case, it is time for the dojo/Request/Registry to debut.
The registration mechanism dojox contains a module dojox/IO/xhrplugins that has existed for a long time but has not been widely used. This module makes dojo. xhr * an interface for all requests, whether sent through jsonp, IFRAME, or even other user-defined methods. The idea of this unified interface is very useful, so it is used in Dojo/Request/Registry.
Dojo/Request/registry also follows the dojo/request API (so it can be used as a provider), but adds a register function:

// If a request URL is "Some/url", the provider will be used to process the request registry. register ("Some/url", provider); // if a request URL starts with "Some/url", the provider will be used to process the request registry. register (/^ some \/URL/, provider); // if a request is sent using an http get method, the provider is used to process the request registry. register (function (URL, options) {return options. method = "get" ;}, provider); // if it cannot match any registered conditions, the default provider will be used
If none of the conditions are met and no standby provider is available, the default provider in the current environment will be enabled. Since dojo/Request/Registry complies with the dojo/request API, it can be used as the default provider:
<script>    var dojoConfig = {        requestProvider: "dojo/request/registry"    };</script><script src="path/to/dojo/dojo.js"></script><script>    require(["dojo/request", "dojo/request/script"],        function(request, script){            request.register(/^\/jsonp\//, script);            ...        }    );</script>
If we want to use the default provider of the Platform (xhr for the browser) as the backup, it is good to do so, but we can also set our backup provider through the last statement in the previous example, after this sentence, you cannot register other providers. The dojo/Request/Registry set on the requestprovider parameter can also accept the plug-in as the standby provider:
<script>    var dojoConfig = {        requestProvider: "dojo/request/registry!my/authProvider"    };</script><script src="path/to/dojo/dojo.js"></script><script>    require(["dojo/request", "dojo/request/script"],        function(request, script){            request.register(/^\/jsonp\//, script);            ...        }    );</script>
Now, all requests that do not meet the Preset conditions will be processed by my/authprovider.
The powerful functions of provide registration are not so obvious. Now let's look at a few scenarios where the registration function can be used. First, consider an application. Its server-side APIs are constantly changing. That is to say, although we know each specific terminal service, we do not know what kind of header information will be required, or even what kind of JSON object will be returned in the response. We can easily register a temporary provider for each service and immediately start to develop the user interface. Assume that/service1 will return JSON data items in the items attribute, and/service2 will return these data items in the data attribute:
request.register(/^\/service1\//, function(url, options){    var promise = xhr(url, lang.delegate(options, { handleAs: "json" })),         dataPromise = promise.then(function(data){            return data.items;        });    return lang.delegate(dataPromise, {        response: promise.response    });});request.register(/^\/service2\//, function(url, options){    var promise = xhr(url, lang.delegate(options, { handleAs: "json" })),         dataPromise = promise.then(function(data){            return data.data;        });    return lang.delegate(dataPromise, {        response: promise.response    });});
All service requests used in the user interface can be used in the form of request (URL, options). Then (...), and all requests receive the correct data. As the development process progresses, a server team may decide to change/service1 to return data items in JSON format in the data attribute, while/service2 will return data items in XML format. If you do not use the registration mechanism, this will cause a lot of code changes. With the registration mechanism, we have decoupled our widgets from the interfaces required by store and the interfaces provided by services, this means that the decisions made by the server team only lead to two code changes: in our two providers. Theoretically, we can even further decouple the user interface from the URL. By using a common URL, our registration mechanism will automatically map the correct service terminal to the correct provider. This avoids a large number of front-end code modifications caused by changes to the service terminal.
This decoupling can also be extended to testing. Remote services are usually unavailable in unit tests: Remote Data may change and remote servers may become unavailable. This is why static data is recommended for testing. However, if our widgets and user interfaces have completely written service terminals and corresponding requests, how can we test them? If we use dojo/Request/Registry, we only need to register a provider dedicated to returning static data for the test task. All API calls do not need to be modified, existing applications do not need to rewrite any code.
The conclusion is that dojo/request is written for developers: simple APIs are available for simple scenarios, and flexible options are available for complex scenarios.
For more information about dojo/request, see:
  • Ajax with dojo/request tutorial
  • Dojo/request Reference Guide
  • Dojo/request API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.