Frontend to Backend: How to Pass JSON Data in URL Parameters

introduction

In web development, we often need to pass data as URL parameters. When we need to pass a complex data structure, how to convert it to a string on the front end and parse it correctly on the back end? This article will introduce how to URL-encode JSON data at the front end, and parse it into the corresponding data type at the back end, and provide sample code in the Java language.

Pass JSON data using URL parameters on the front end

Sometimes we need to pass JSON data from the front end to the back end, such as through AJAX requests or page jumps. URL parameters are a common way to transfer data, but because URL parameters only support string type data, and JSON data is a complex data type, encoding and decoding operations are required.

In JavaScript, we can use JSON.stringify()the method to convert a JSON object to a string, and then use encodeURIComponent()the method to URL-encode the string. Here's an example of sending an AJAX request with JSON data as URL parameters:

const data = {
    
     name: 'John', age: 30 };
const encodedData = encodeURIComponent(JSON.stringify(data));

fetch(`/api/user?data=${
      
      encodedData}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In the example above, we first created a JSON object with two properties data, then converted it to a string and URL-encoded it. We then use fetch()the method to send a dataGET request with the parameter, and in the response use json()the method to parse the response body into a JSON object.

Parse URL parameters on the backend

In the backend, we need to parse the URL parameters sent from the frontend containing JSON data. Different backend languages ​​and frameworks may have different parsing methods. Here we take Node.js and Java as examples to introduce how to parse URL parameters.

Parsing URL parameters in Node.js

In Node.js, we can use the built-in urlmodule to parse URL parameters and querystringthe module to parse query string parameters. Here's an example of parsing URL parameters using Node.js:

const http = require('http');
const url = require('url');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
    
    
  const parsedUrl = url.parse(req.url);
  const parsedQuery = querystring.parse(parsedUrl.query);

  // 解析包含在 'data' 参数中的 JSON 字符串
  const rawData = parsedQuery.data;
  const myObject = JSON.parse(decodeURIComponent(rawData));

  // 执行其他操作...

  res.writeHead(200, {
    
     'Content-Type': 'text/plain' });
  res.end('Hello World!');
});

server.listen(3000, () => {
    
    
  console.log('Server running on port 3000');
});

In the above example, we first use url.parse()the method to parse the request URL into a URL object, and then use querystring.parse()the method to parse the query string parameters into an object. We then get the raw data containing the JSON string from datathe parameter , decodeURIComponent()decode the string using and JSON.parse()parse .

Parsing URL parameters in Java

In Java, we can use java.net.URLDecoderclass and java.util.Mapinterface to parse URL parameters. Here is an example of parsing URL parameters in Java:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class Main {
    
    
  public static void main(String[] args) throws UnsupportedEncodingException {
    
    
    String urlString = "http://localhost:3000/?data=%7B%22name%22%3A%22John%22%2C%22age%22%3A30%7D";
    String[] urlParts = urlString.split("\\?");
    String query = urlParts.length > 1 ? urlParts[1] : "";
    Map<String, String> queryMap = new HashMap<>();
    for (String param : query.split("&")) {
    
    
      String[] pair = param.split("=");
      String key = URLDecoder.decode(pair[0], "UTF-8");
      String value = URLDecoder.decode(pair[1], "UTF-8");
      queryMap.put(key, value);
    }

    // 解析包含在 'data' 参数中的 JSON 字符串
    String rawData = queryMap.get("data");
    String json = URLDecoder.decode(rawData, "UTF-8");
    JSONObject myObject = new JSONObject(json);

    // 执行其他操作...
  }
}

In the above example, we first split the request URL into a base part and a query string part, and then parse the query string parameters into a Map object of key-value pairs. We then take the raw data containing the URL-encoded JSON string from datathe parameter , URLDecoder.decode()decode the string using the , and parse it into a Java object using JSONObjectthe class .

Summarize

When using URL parameters to pass JSON data at the front end, the JSON data needs to be converted to a string and URL-encoded first. When parsing URL parameters in the backend, you need to first decode the URL-encoded string into raw data and parse it into the corresponding data type. Different backend languages ​​and frameworks may have different parsing methods, but the basic principles are the same.

Guess you like

Origin blog.csdn.net/huangge1199/article/details/130383863