Angularjs Learning Notes (iv)----communication with back-end servers

Source: Internet
Author: User

I. Use of $http for XHR and JSONP requests

  1.1 XHR Request

    • Get: $http. Get (Url,config)
    • Post: $http. Post (Url,data,config)
    • Put: $http. Put (Url,data,config)
    • Delete: $http. Delete (Url,config)
    • Head: $http. Head

  1.2 Jsonp Request

$http. JSONP (Url,config)

  1.3 Method Parameter Description

    • URL: Call Destination URL
    • Data: Sent in the request body
    • Config: JavaScript configuration object with additional configuration information that affects both requests and responses

  1.4 Config Description

JavaScript Configuration objects hold a number of options to affect the requested, corresponding, and transmitted data. The more important properties in the configuration object are as follows:

    • Method: The HTTP methods used
    • URL: The destination URL of the request
    • Parameters of the Params:url
    • Headers: Extra Request Header
    • TIMEOUT:XHR time-out before request termination (in milliseconds)
    • CACHE:XHR Cache switch for GET requests
    • Transformrequest, Transpormresponse: A Data transformation function that processes data before or after exchanging data with the backend

1.5 Conversion of request data and corresponding data

The $http. Post and $http.put methods accept any JavaScript object (or string) value as their data parameter. If data is a JavaScript object, data is converted to a JSON string by default.

As with the transform request data, the $http service attempts to convert the JSON string contained in the response to a JavaScript object, which occurs before a success or failure callback, and the default conversion behavior can be customized.

  1.6 Handling HTTP Responses

  The request may succeed or fail, ANGULARJS provides two methods to register callbacks corresponding to these two outcomes; success and error. They all accept the callback function, which invokes the following parameters:

    • Data: The actual response
    • Status: HTTP status of the response
    • Headers: Functions to access HTTP response header information
    • Config: The configuration object provided when the request is triggered

Second, deal with the same-Origin policy constraints

Web browsers enforce the same-origin security policy, which only XHR interactive authorization of target resources from the same source (protocol, host, and Port) and restricts the interaction of external resources.

Here are three ways to access data from an external server:

  2.1 JSONP

Using JSONP, you can get data beyond the same-Origin policy constraints. Its implementation depends on the browser being able to freely access JavaScript from an external server via the <script> tag.

The JSONP call does not trigger the XHR request, instead generates a <script> tag whose source points to the external resource.

How to use:

$http    . Jsonp (' Http://angularjs.org/greet.php?callback=JSON_CALLBACK ', {        params:{            name: ' World '        }    }). Success (function (data) {        $scopt. greeting=data;    });        

JSONP restrictions. First, get HTTP requests can only be submitted with JSONP technology, and second, error handling is cumbersome because the browser does not expose HTTP response status through <script> tags. In practice, this means that it is difficult to report an HTTP status error and invoke an error callback.

Jsonp also poses some potential security issues for Web applications. For example, a well-known XSS attack, so you should carefully select the target service for the JSONP request, just use a trusted server.

  2.2 CORS

 CORS (cross-origin resource sharing) is a package of standards, committed to the standard, reliable and safe to solve the problems faced by the jsonp above. The Cors standard is based on the XMLHttpRequest object, with a clear and controllable way of cross-domain AJAX requests.

The philosophy of Cors is that browsers and external servers need to collaborate (by sending the appropriate request and response headers) for conditional cross-domain requests. The external server needs to be configured sequentially, and the browser must send the appropriate request and request headers and translate the server response to successfully complete the cross-domain request.

Cons: ① needs to be configured. ② $http Service does not support cors requests under IE8 and IE9.

  2.3 Server-side proxy

Jsonp is not the ideal technology for cross-domain requests. Although the Cors standard is good, it still requires additional configuration on the server side and a browser that supports this standard.

If you cannot use Cors and JSONP technology, there is also a way to avoid cross-domain requests, which is to configure the local server for external servers as proxies. By applying the correct server configuration, cross-domain requests can be proxied through your own server, so the browser will only target the server. This technique works on all browsers and does not need to be tested with the options request. And we don't have to take any security risks. The only downside to this approach is that we still need to configure the server.

Third, Promise API and $q 

  3.1 Promise

In the world of asynchrony, we cannot simply link function calls, but rather rely on callbacks, which work well when dealing with only one asynchronous event, but when it comes to reconciling multiple asynchronous events, things begin to become complex, and it is particularly difficult to get asynchronous state processing.

But with promise, it can help developers write asynchronous code in a synchronous way, such as in Angularjs:

Deferabc.resolve (XXX). Then (Funcsuccess () {},funcerror () {},funcnotify () {});

When an object inside the resolve executes successfully, the funcsuccess is triggered and funcerror is triggered if it fails.

To put it bluntly, promise is a kind of pre-defined definition of the result of execution, if successful, XXXX; if it fails, it is like giving some promise in advance.

  3.2 $q

  3.2.1 Definition

$q Service is a promise implementation of ANGULARJS in its own package implementation.

  3.2.2 Status

In promise, three states are defined: Wait, completion, and deny status.

There are several rules regarding status:

    • 1 The change of state is irreversible
    • 2 wait status can become complete or reject

3.2.3   Several methods commonly used in $q

    • Defer () Creates an deferred object that can perform several common methods, such as resolve,reject,notify, etc.
    • All () An array of incoming promise, executed in bulk, returning a Promise object
    • When () passes in an indeterminate parameter and returns a Promise object if it conforms to the promise standard. 

3.2.4 Defer () method

  In $q, you can use the Resolve method to become a completion state, and use the Reject method to become a deny state.

"myApp">"Content-type"Content="text/html; Charset=utf-8"/> <script src="Http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>"Myctrl">{{Test}}</div> <script type="Text/javascript">varMyappmodule = Angular.module ("myApp",[]); Myappmodule.controller ("Myctrl",["$scope","$q", Function ($scope, $ q) {$scope. Test=1;//This is just for testing the ANGULARJS, no other function .            varDefer1 =$q. Defer (); varPromise1 =defer1.promise; Promise1. Then (function (value) {Console.log ("In promise1----Success");            Console.log (value); },function (value) {Console.log ("In promise1----error");            Console.log (value); },function (value) {Console.log ("In promise1----Notify");            Console.log (value); })            .Catch(function (e) {Console.log ("In promise1----Catch");            Console.log (e); })            .finally(function (value) {Console.log ('In promise1----finally');            Console.log (value);            }); Defer1.resolve ("Hello"); //defer1.reject ("Sorry,reject");         }]); </script></body>

 where defer () is used to create a deferred object, Defer.promise is used to return a Promise object to define the then method. Then there are three parameters, namely the success callback, the failure callback, and the state change callback.

Where the variable or function passed in resolve returns the result, it is treated as a parameter of the first then method. The then method returns a Promise object, so it can be written as

Xxxx.then (a,b,c). Then (A,b,c). Then (a,b,c). Catch (). finally ()

  Keep talking about the above code, then...catch...finally can think of Java inside the try...catch...finally.

  3.2.5 All () method

 This all () method can combine multiple primise arrays into one. When all promise executes successfully, the subsequent callback is executed. The parameters in the callback are the results of each promise execution.
You can use this method when you execute certain methods in bulk.

varFunca =function () {Console.log ("Funca"); return "Hello,funa"; }            varFUNCB =function () {Console.log ("FUNCB"); return "Hello,funb";            $q. All ([Funca (), FUNCB ()]). Then (function (Result) {Console.log (result); });

Results of execution

" Hello,funa " " Hello,funb "

  3.2.6 When () method

The When method can pass in a parameter, which may be a value, possibly an external object that conforms to the promise standard.

var funca = function () {                console.log ("funca");                 return " Hello,funa " ;            }            $q. When (Funca ())            . Then (function (Result) {                console.log (result);            });

  Results of execution

Hello,funa

Part of the above excerpt from http://www.cnblogs.com/xing901022/p/4928147.html

Reference Document HTTP://WWW.NGNICE.COM/POSTS/126EE9CF6DDB68

Angularjs Learning Notes (iv)----communication with back-end servers

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.