


Solution to the problem that $http asynchronous background cannot obtain request parameters in AngularJS
Dec 08, 2016 am 09:48 AMThe example in this article describes the solution to the problem that the $http asynchronous background cannot obtain the request parameters in AngularJS. Share it with everyone for your reference, the details are as follows:
angular uses a different request header and data serialization method than jQuery when submitting data asynchronously, causing some background programs to be unable to parse the data normally.
Principle analysis (online analysis):
For AJAX applications (using XMLHttpRequests), the traditional way to initiate a request to the server is: obtain a reference to an XMLHttpRequest object, initiate the request, read the response, check the status code, and finally Handle server response. An example of the entire process is as follows:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(xmlhttp.readystate == 4 && xmlhttp.status == 200) { var response = xmlhttp.responseText; }else if(xmlhttp.status == 400) { //或者可以是任何以4開頭的狀態(tài)碼 //優(yōu)雅地處理錯(cuò)誤 } }; //建立連接 xmlhttp.open("GET", "http://myserver/api", true); //發(fā)起請(qǐng)求 xmlhttp.send();
For simple, common and frequently repeated tasks, this is a very tedious task. If you want to reuse the above process, you should encapsulate it or use a code library.
AngularJS XHR API adheres to an interface commonly known as Promise. Since XHR is an asynchronous call method, the server's response will be returned at an uncertain point in time in the future (we hope it will be returned immediately). The Promise interface specifies how to handle this response and allows users of Promise to use it in a predictable way.
For example, we want to obtain a user's information from the server. Assume that the backend interface used to accept requests is located on the /api/user path. This interface can accept an id attribute as a URL parameter, then use Angular's core $http service An example of how to initiate an XHR request is as follows:
$http.get('api/user', {params: {id:'5'} }).success(function(data, status, headers, config) { //加載成功之后做一些事 }).error(function(data, status, headers, config) { //處理錯(cuò)誤 });
If you are a jQuery user, you should find that AngularJS and jQuery are very similar in handling asynchronous requests.
The $http.get method used in the above example is one of the many shortcut methods provided by AngularJS's core service $http. Similarly, if you want to use AngularJS to send a POST request to the same URL, along with some POST data, you can do it like this:
var postData = {text:'long blob of text'}; //下面這一行會(huì)被當(dāng)成參數(shù)附加到URL后面,所以post請(qǐng)求最終會(huì)變成/api/user?id=5 var config = {params: {id: '5'}}; $http.post('api/user', postData, config ).success(function(data, status, headers, config) { //成功之后做一些事情 }).error(function(data, status, headers, config) { //處理錯(cuò)誤 });
For most common request types, there are similar Shortcut methods, these request types include: GET, HEAD, POST, DELETE, PUT, JSONP.
1. Further configure the request
Although the standard request method is relatively simple to use, it sometimes has the disadvantage of poor configurability. You will encounter difficulties if you want to implement the following things:
a. Add some authorization headers to the request.
b. Modify the way cache is handled.
c. Use some special methods to transform the sent request or transform the received response.
In these cases, you can deeply configure the request by passing an optional configuration object to the request. In the previous example, we specified an optional URL parameter using the config object. But the GET and POST methods there are some shortcuts. An example of method calling after this deep simplification is as follows:
$http(config)
The following is a basic pseudocode template for calling the previous method:
$http({ method: string, url: string, params: object, data: string or object, headers: object, transformRequest: function transform(data, headersGetter) or an array of functions, transformResponse: function transform(data, headersGetter) or an array of functions, cache: boolean or Cache object, timeout: number, withCredentials: boolean });
GET, POST and other shortcuts Methods will automatically set method parameters, so there is no need to set them manually. The config object will be passed as the last parameter to $http.get and $http.post, so this parameter can be used inside all shortcut methods. You can pass a config object to modify the request sent. The config object can set the following key values.
method: a string indicating the type of HTTP request, such as GET or POST.
url: URL string, indicating the requested absolute or relative resource path.
params: An object whose keys and values ??are both strings (a map to be exact), representing the keys and values ??that need to be converted into URL parameters. For example:
[{key1: 'value1', key2: 'value2'}]
will be converted to
?key1=value&key2=value2
and will be appended to the URL. If we use a js object (rather than a string or value) as the value in the map, then the js object will be converted into a JSON string.
data: A string or object, which will be sent as request data.
timeout: The number of milliseconds to wait before the request times out.
2. Set HTTP headers
AngularJS comes with some default request headers, and all requests issued by Angular will have these default request headers. The default request headers include the following two:
1.Accept:application/json,text/pain,/
2.X-Requested-With: XMLHttpRequest
If you want to set special request headers, you can use the following two methods. .
The first method, if you want to set the request header to every request sent out, then you can set the special request header to be used to the default value of AngularJS. These values ??can be set via the $httpProvider.defaults.headers configuration object, usually in the configuration section of the application. So, if you want to use the "DO NOT TRACK" header for all GET requests and remove the Requested-With header for all requests, you can simply do the following:
angular.module('MyApp', []). config(function($httpProvider) { //刪除AngularJS默認(rèn)的X-Request-With頭 delete $httpProvider.default.headers.common['X-Requested-With']; //為所有GET請(qǐng)求設(shè)置DO NOT TRACK $httpProvider.default.headers.get['DNT'] = '1'; });
如果你只想對(duì)某些特定的請(qǐng)求設(shè)置請(qǐng)求頭,但不把它們作為默認(rèn)值,那么你可以把頭信息作為配置對(duì)象的一部分傳遞給$http服務(wù)。同樣的,自定義頭信息也可以作為第二個(gè)參數(shù)的一部分傳遞給GET請(qǐng)求,第二個(gè)參數(shù)還可以同時(shí)接受URL參數(shù)。
$http.get('api/user', { //設(shè)置Authorization(授權(quán))頭。在真實(shí)的應(yīng)用中,你需要到一個(gè)服務(wù)里面去獲取auth令牌 headers: {'Authorization': 'Basic Qzsda231231'}, params: {id:5} }).success(function() {//處理成功的情況 });
三.緩存響應(yīng)
對(duì)于HTTP GET請(qǐng)求,AngularJS提供了一個(gè)開箱即用的簡(jiǎn)單緩存機(jī)制。默認(rèn)情況下它對(duì)所有請(qǐng)求類型都不可用,為了啟用緩存,你需要做一些配置:
$http.get('http://server/myapi', { cache: true }).success(function() {//處理成功的情況});
這樣就可以啟用緩存,然后AngularJS將會(huì)緩存來(lái)自服務(wù)器的響應(yīng)。下一次向同一個(gè)URL發(fā)送請(qǐng)求的時(shí)候,AngularJS將會(huì)返回緩存中的響應(yīng)內(nèi)容。緩存也是智能的,所以即使你向同一個(gè)URL發(fā)送多次模擬的請(qǐng)求,緩存也只會(huì)向服務(wù)器發(fā)送一個(gè)請(qǐng)求,而且在收到服務(wù)端的響應(yīng)之后,響應(yīng)的內(nèi)容會(huì)被分發(fā)給所有請(qǐng)求。
但是,這樣做有些不太實(shí)用,因?yàn)橛脩魰?huì)先看到緩存的舊結(jié)果,然后看到新的結(jié)果突然出現(xiàn)。例如,當(dāng)用戶即將點(diǎn)擊一條數(shù)據(jù)時(shí),它可能會(huì)突然發(fā)生變化。
注意,從本質(zhì)上來(lái)說(shuō),響應(yīng)(即使是從緩存中讀取的)依然是異步的。換句話說(shuō),在第一次發(fā)出請(qǐng)求的時(shí)候,你應(yīng)該使用處理異步請(qǐng)求的方式來(lái)編碼。
四.轉(zhuǎn)換請(qǐng)求和響應(yīng)
對(duì)于所有通過(guò)$http服務(wù)發(fā)出的請(qǐng)求和收到的響應(yīng)來(lái)說(shuō),AngularJS都會(huì)進(jìn)行一些基本的轉(zhuǎn)換,包括如下內(nèi)容。
1.轉(zhuǎn)換請(qǐng)求
如果請(qǐng)求的配置對(duì)象屬性中包含JS對(duì)象,那么就把這個(gè)對(duì)象序列化成JSON格式。
2.轉(zhuǎn)換響應(yīng)
如果檢測(cè)到了XSRF(Cross Site Request Forgery的縮寫,意為跨站請(qǐng)求偽造,這是跨站腳本攻擊的一種方式)前綴,則直接丟棄。如果檢測(cè)到了JSON響應(yīng),則使用JSON解析器對(duì)它進(jìn)行反序列化。
如果你不需要其中的某些轉(zhuǎn)換,或者想自已進(jìn)行轉(zhuǎn)換,可以在配置項(xiàng)里面?zhèn)魅胱砸训暮瘮?shù)。這些函數(shù)會(huì)獲取HTTP的request/response體以及協(xié)議頭信息,然后輸出序列化、修改之后的版本??梢允褂胻ransformLRequest和transformResponse作為key來(lái)配置這些轉(zhuǎn)換函數(shù),而這兩個(gè)函數(shù)在模塊的config函數(shù)中是用$httpProvider服務(wù)來(lái)配置的。
我們什么時(shí)候需要使用這些東西呢?假設(shè)我們有一個(gè)服務(wù),它更適合用jQuery的方式來(lái)操作。POST數(shù)據(jù)使用key1=val1&key2=val2(也就是字符串)形式來(lái)代替{key1:val1, key2:val2}JSON格式。我們可以在每個(gè)請(qǐng)求中來(lái)進(jìn)行這種轉(zhuǎn)換,也可以添加一個(gè)獨(dú)立transformRequest調(diào)用,對(duì)于當(dāng)前這個(gè)例子來(lái)說(shuō),我們打算添加一個(gè)通用的transformRequest,這樣所有發(fā)出的請(qǐng)求都會(huì)進(jìn)行這種從JSON到字符串的轉(zhuǎn)換。下面就是實(shí)現(xiàn)方式:
var module = angular.module('myApp'); module.config(function($httpProvider) { $httpProvider.defaults.transformRequest = function(data) { //使用jQuery的param方法把JSON數(shù)據(jù)轉(zhuǎn)換成字符串形式 return $.param(data); }; });
實(shí)列配置:
在使用中發(fā)現(xiàn)后臺(tái)程序還是無(wú)法解析angular提交的數(shù)據(jù),對(duì)比后發(fā)現(xiàn)頭部缺少‘X-Requested-With'項(xiàng)
所以在配置中加入:
復(fù)制代碼代碼如下:
$httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'
下面貼入測(cè)試時(shí)的部分配置代碼:
angular.module('app', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ],function ($httpProvider) { // 頭部配置 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript, */*; q=0.01'; $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'; /** * 重寫angular的param方法,使angular使用jquery一樣的數(shù)據(jù)序列化方式 The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function (obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } return query.length ? query.substr(0, query.length - 1) : query; }; // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function (data) { return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; }).config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl' }) .otherwise({ redirectTo: '/' }); });
? ?
希望本文所述對(duì)大家AngularJS程序設(shè)計(jì)有所幫助。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.
