SoFunction
Updated on 2025-04-11

Detailed explanation of post request processing example in angular

Preface

The project uses jQuery request in angular and wants to replace it with angular's own request, but it was found that the background cannot obtain parameters, so, query the information and analyze it, and make a summary.

The steps are as follows:

First of all, requests in angular and jQuery are different. as follows:

  • jQuery:

The requested contentType is:

application/x-www-form-urlencoded; charset=UTF-8

This type of data is encoded into a key-value pair separated by '&', while the key and value are separated by '='. Characters that are not letters or numbers are encoded by percentages: This is why this type does not support binary data (multipart/form-data should be used instead).

The data parameters are processed:

// json object{ a : 3, b : 2 }
// Process the json object as"a=3&b=2"
  • Angular:

Request contentType:

application/json

Data parameters:

// json object{a: 3,c: 2}

To sum up, the angular submission background is json, not form data. We need to convert the json object into parameter stitching, and the form data is the submission of the background:

/**
   * Convert application/json to application/x-www-form-urlencoded
   * @param data
   */
 handlerPostParams(data) {
  const params = [];
  for (const key in data) {
   if (data[key] && !isNull(data[key])) {
    if (data[key] instanceof Array) {
     for (let i = 0; i < data[key].length; i++) {
      if (data[key][i] && !isNull(data[key][i])) {
       const value = data[key][i];
       const name = key + '[' + i + ']';
       const innerObj = {};
       innerObj[name] = value;
       ((innerObj));
      }
     }
    } else if (data[key] instanceof Object) {
     for (const k in data[key]) {
      if (data[key][k] && !isNull(data[key][k])) {
       const value = data[key][k];
       const name = key + '[' + k + ']';
       const innerObj = {};
       innerObj[name] = value;
       ((innerObj));
      }
     }
    } else {
     const param = encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
     (param);
    }
   }
  }
  return ('&');
 }

Summarize

This is the end of this article about post request processing in angular. For more related angular post request processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!