Because the project needs to be sent to the background of the data in the form of formdata data sent to the background, access to a lot of data found a solution to share with you. In addition, $httpparamserializerjqlike data is formatted to follow the jquery serialization specification.
The main use of transformrequest data serialization, pay attention to the Content-type must be set to undefined, so that the browser will automatically help you set the Formdata separator, your own settings will be wrong. A better solution is also available in the comments below.
HTTP requests are configured here, put and delete are resource plug-ins, except get, other requests are sent by default in the form of formdata, and can be redefined in transformrequest app.service (' Myhttp ', [' $http ', ' $resource ', function ($http, $resource) {/////Note formdata Send data request must be ' content-ty PE ', set to undefined, such as headers:{' Content-type ': undefined} var setformdata=function (data) {var myform=new formda
Ta (); Type judgment if (typeof data== "Object") {Angular.foreach (data, function (V, k) {if (Typeo
F v!= "Object") {//Not object is added directly to Formdata Myform.append (k, v);//(parameter name, parameter value)
}else{//If the object is to convert the object to a string format, use it more for the array object Myform.append (k, Angular.tojson (v));
}
});
return MyForm;
}; The following uses Setformdata to send data var httpr= $resource ('/v1/admin/:mytype/:id ', {mytype: ' @mytype ', id: ' @id '}, {REM Ove: {method: "DELETE", headers:{' Content-type ': undefined},transforMrequest:function (data) {return setformdata (data);
}, Update: {method: ' Put ', headers:{' Content-type ': undefined},transformrequest:function (data) {
return Setformdata (data);
}}
});
/*post Request */self.httppost=function (obj) {def.config={headers: { ' Content-type ': undefined}, transformrequest:function (data) {Retur
n Setformdata (data);
}
};
Obj=angular.extend (Def,obj);
$http. Post (Obj.url,obj.data,obj.config). Success (function (data) {Console.log (data);
}). Error (function (data) {Console.log (data,obj);
});
}; Self.resupdate=function (obj) {httpr.update (obj.data,obj.config,function (data) {Console.log
(data);
},function (data) { Console.log (Data,obj);
})
}; Self.resdelete=function (obj) {httpr.remove (obj.data,obj.config,function (data) {Console.log
(data);
},function (data) {Console.log (data,obj);
});
}; }]);
Described above is serialized as Formdata, and here is another serialization service ' $httpParamSerializerJQLike ', which supports angular1.4.0 above.
$httpParamSerializerJQLike can serialize data sent by HTTP into a format that follows the jquery serialization specification. It's easy to use.
Transformrequest:function (data) {
var newdata = $httpParamSerializerJQLike (data);
Return NewData
}
With good advice and comments, you are welcome to leave a comment in the comments section.
’