AngularJS $http post 传递参数数据

在cordova开发的时候使用到了$http的post方法,传递的参数服务端怎么都接收不到,搜索了下,发现使用AngularJS通过POST传递参数还是需要设置一些东西才可以!

1、不能直接使用params

例如:

  1. $http({
  2. method: "POST",
  3. url: "http://192.168.2.2:8080/setId",
  4. params: {
  5. cellphoneId: "b373fed6be325f7"
  6. }
  7. }).success();



当你这样写的时候它会把id写到url后面:
http://192.168.2.2:8080/setId?cellphoneId=b373fed6be325f7"
会在url后面添加"?cellphoneId=b373fed6be325f7",查了些资料发现params这个参数是用在GET请求中的,而 POST/PUT/PATCH 就需要使用data来传递;

2、直接使用data

  1. $http({
  2. method: "POST",
  3. url: "http://192.168.2.2:8080/setId",
  4. data: {
  5. cellphoneId: "b373fed6be325f7"
  6. } }).success();


这样的话传递的,是存在于Request Payload中,后端无法获取到参数


这时发现Content-Type:application/json;charset=UTF-8,而POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,所以需要把Content-Type修改下!

3、修改Content-Type

  1. $http({
  2. method: "POST",
  3. url: "http://192.168.2.2:8080/setId",
  4. data: { cellphoneId: "b373fed6be325f7"},
  5. headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  6. }).success();


这时数据是放到了Form Data中但是发现是以对象的形式存在,所以需要进行序列化!

4、对参数进行序列化

  1. $http({
  2. method: "POST",
  3. url: "http://192.168.2.2:8080/setId",
  4. data: {cellphoneId: "b373fed6be325f7"},
  5. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  6. transformRequest: function(obj) {
  7. var str = [];
  8. for (var s in obj) {
  9. str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
  10. }
  11. return str.join("&");
  12. }
  13. }).success();

猜你喜欢

转载自blog.csdn.net/luoxiping1/article/details/80968279