"Minimalist and practical" use the qs library to parse URL query strings!

"qs" usually means "querystring" and refers to a processing library for query strings in URLs that parses, serializes, and creates query strings. It is very useful for building web applications in front-end (browser) and back-end (Node.js), which can conveniently handle data exchange with back-end servers. The following is an example of the use of qs:

  1. Install the qs library:
npm install qs
  1. Serialized object:
const qs = require('qs');

const params = {
    
    
  id: 1,
  name: 'apple',
  price: 3.5
};

const querystring = qs.stringify(params);
console.log(querystring); // 输出: 'id=1&name=apple&price=3.5'
  1. Parse the query string:
const qs = require('qs');

const querystring = 'id=1&name=apple&price=3.5';
const params = qs.parse(querystring);
console.log(params); // 输出: {id: "1", name: "apple", price: "3.5"}
  1. More advanced parsing:
const qs = require('qs');

const querystring = 'id=1&name=apple&price=3.5';
const params = qs.parse(querystring, {
    
    ignoreQueryPrefix: true, depth: 2});

console.log(params); // 输出: {id: 1, name: 'apple', price: 3.5}

In this example, we used the "ignoreQueryPrefix" option to instruct to skip the query prefix (such as "?") and parse the query string. We also use the "depth" option to specify the maximum nesting depth.

Guess you like

Origin blog.csdn.net/weixin_46286150/article/details/129992896
Recommended