This article describes the Angularjs ng Http request and the response format conversion method. Share to everyone for your reference, specific as follows:
The interactive approach recommended by angular as a single Page application is of course based on JSON Ajax calls. But what I'm saying today is that when you're unlucky enough to work on a legacy or uncontrollable service that is based on non-JSON submissions (perhaps a regular form submission, or other custom data format), then we can only change Ng's internal $http default request/ Response format Conversion Mode.
Fortunately, Ng $http provides us with a variety of ways to transform data formats (the following demo will take form submission as an example):
For some separate HTTP request settings:
The last parameter for HTTP Ajax is all about HTTP configuration information, including a transformrequest, we can use Transformrequest to change the format of the data before Ajax sends the data, such as the demo below:
$http. Post ("/url", {
id:1,
name: "Greengerong"
}, {
transformrequest:function (request) {
return $.param (Request);
}
);
Here we use jquery's $.param to format the form submission, so we can see the request body as:
For HTTP request settings for the entire app:
If we need to set up the data conversion format for the entire HTTP, you can use the Config phase to set the $httpprovider default behavior:
Angular.module ("App", [])
. config (["$httpProvider", function ($httpProvider) {
$ HttpProvider.defaults.transformRequest = [
function (Request) {return
$.param (request);
}
];
}
];
This way we can easily convert to form submission.
The same $http provides us with a transformresponse approach, and we can also create our own response transformations, such as adding a custom prefix before JSON to prevent JSON array attacks, and so on.
I hope this article will help you to Angularjs program design.