ANGULAR $HTTP Request

Source: Internet
Author: User

Angular issues with post, get to background

I. Source of the problem

We all know that a background pass can use GET, put, which is similar to name=jyy&id=001. But in Ng I found that the background was not receiving data during asynchronous transfer using $http post. In fact, this problem is due to the request of the head. The default request header in Ng is: "Content-type": "Application/json", which means that the pass-through parameter is in JSON format. But the backstage default is Content-type ': ' application/x-www-form-urlencoded '. So in this case the data received in the background will be empty.

So why use the Get form to pass the argument? In the book I found this sentence: "The value of this key is a string map or object, will be converted into a query string appended to the URL." If the value is not a string, it will be serialized by JSON ", it can be understood that in get parameters are appended directly after the URL, then the Parameter form {" id ":" 1 "," name ":" Jyy "} will be converted to id=1&name=jyy appended after the URL. Then you can get it directly in the background. For example:

var app = Angular.module (' app ', []);        App.controller (' Ctrl ', function ($scope, $q, $http) {            var defer = $q. Defer ();            var promise = Defer.promise;            $http ({                method: "Get",                params:{id:1,name:jyy},                URL: "1.php"            }). Success (function (data) {                Defer.resolve (data);            });            Promise.then (function (data) {                $scope. data = data;            })        })

In the background (PHP) input echo $_get[id] can be displayed normally.

Then we will study how to solve the post value.

Second, the problem of the solution

1. Modify the request header

The first method is to modify the request header in Ng to change the JSON format to x-www-form-urlencoded. Modify the method click to view.

It is important to note that when you use the second method, you can modify the Put,get,post,common parameter format. So modify which way, you can only use this way to get the parameters in the background. This blog post says that using common to set up can use both a put, get, and post to pass parameters. However, in my actual operation, I found that the common was modified and could not use post to pass the parameter, and only the request header with post was set.

In addition, since the parameters in Ng are expressed in JSON format, jquery needs to be introduced, using its $.param (the JSON format of the parameter list) to serialize the representation.

First use the Modify POST request header. The specific code is as follows:

var app = Angular.module (' app ');        App. Config (function ($httpProvider) {            $httpProvider. defaults.headers.post = {' Content-type ': ' application/ X-www-form-urlencoded '}        })        app.controller (' Ctrl ', function ($scope, $resource, $q, $http) {            var defer = $ Q.defer ();            var promise = Defer.promise;            $http ({                method: "Post",                Data:$.param ({"id": "1", "name": "Jyy"}),                URL: "1.php"            }). Success (function (data) {                defer.resolve (data);            });            Promise.then (function (data) {                $scope. data = data;            })        })

At this point in the background (using PHP), enter Echo $_post[id], it will be displayed. The request header shown in debug is exactly what we set up.

 2. In the background to resolve

  Because PHP is used, it is temporarily solved by PHP method. In this method, we do not modify the request header. Because the get pass value is normal, it is good to get the value of the post. Since NG passes the value in the background, even if the request head is different, but always pass over what, since can pass over, get it first. This time use $globals[' Http_raw_post_data '] to show the things that pass through. So what is this $globals[' Http_raw_post_data '? The online query learns $HTTP_RAW_POST_DATA that the variable contains the original POST data. This variable is only generated when it encounters an unrecognized MIME type of data, and when PHP does not recognize the Content-type type, the corresponding data in the HTTP request packet is populated with the variable $http_raw_post_data. This means that the request header is now in conflict, but it can be displayed. As follows:

var app = Angular.module (' app ', []);        App.controller (' Ctrl ', function ($scope, $q, $http) {            var defer = $q. Defer ();            var promise = Defer.promise;            $http ({                method: "Post",                data:{' id ': ' 1 ', ' name ': ' Jyy '},                URL: "1.php"            }). Success (function (data) {                defer.resolve (data);            });            Promise.then (function (data) {                $scope. data = data;            })        })

PHP Code:

echo $GLOBALS [' http_raw_post_data '];

The thing that appears is: {"id": "1", "name": "Jyy"}. Found that the results were displayed correctly. So the direct alignment of the operation is not possible? Well, let's see what it is. Type: Using GetType () to get a string, that is, he is a JSON string. Then use the Json_decode () conversion to find an error. Well, give up using this method.

But there is another way to do this. Using file_get_contents ("Php://input"), this method php://input is a read-only stream that can access the raw data of the request. POST request, it is best to use php://input instead of the $HTTP _raw_post_data because it does not depend on a specific php.ini directive. At this point the method can return the passed parameters. The code is as follows:

$a = Json_decode (file_get_contents ("Php://input"));    Echo $a->id;

The result outputs the correct ID.

Reprinted from: http://www.cnblogs.com/liuhongjin/p/6202141.html

ANGULAR $HTTP Request

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.