当前位置:首页 » 《我的小黑屋》 » 正文

前端传输数组类型到后端(附代码)

17 人参与  2024年04月19日 16:47  分类 : 《我的小黑屋》  评论

点击全文阅读


文章目录

前言1. 问题所示2. 普通数组3. JSON格式4. 彩蛋

前言

通过问题Bug指引代码实战,结合实战问题,相应查漏补缺

1. 问题所示

前端传输数组给后端的时候,出现如下问题:

前端log请求如下:
在这里插入图片描述

且请求后端你的时候出现了服务器500error:

在这里插入图片描述

2. 普通数组

如果不使用 JSON 格式传输数据,而是使用普通的数组,可以考虑通过 POST 请求的 body 直接传输数组的形式

前端,可以将数组直接作为请求的 body后端,可以直接接收请求的 body 作为数组进行处理

前端数据:

<template>  <div>    <!-- 按钮触发事件 -->    <button @click="sendArrayToBackend">发送数组到后端</button>  </div></template><script>export default {  methods: {    sendArrayToBackend() {      const array = ['a', 'b', 'c'];      // 发送数组到后端      fetch('http://localhost:8080/processArray', {        method: 'POST',        body: array.join(',') // 将数组转换成逗号分隔的字符串作为请求的 body      })      .then(response => response.text())      .then(result => console.log(result))      .catch(error => console.error('Error:', error));    }  }}</script>

后端代码:

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestControllerpublic class BackendApplication {    public static void main(String[] args) {        SpringApplication.run(BackendApplication.class, args);    }    @PostMapping("/processArray")    public String processArray(@RequestBody String[] array) {        // 处理收到的数组        for (String element : array) {            System.out.println(element);        }        return "Array processed successfully";    }}

在这个示例中,前端使用 array.join(',') 将数组转换成逗号分隔的字符串,然后作为请求的 body 直接发送到后端的 /processArray 接口。后端接收到字符串后,根据逗号分隔拆分成数组进行处理

3. JSON格式

前端通过点击按钮触发sendArrayToBackend方法,该方法使用Fetch API将数组发送到后端的/processArray接口。后端接收到数组后进行处理,并返回响应。

前端代码:

<template>  <div>    <!-- 按钮触发事件 -->    <button @click="sendArrayToBackend">发送数组到后端</button>  </div></template><script>export default {  methods: {    sendArrayToBackend() {      const array = ['a', 'b', 'c'];      // 发送数组到后端      fetch('http://localhost:8080/processArray', {        method: 'POST',        headers: {          'Content-Type': 'application/json'        },        body: JSON.stringify(array)      })      .then(response => response.text())      .then(result => console.log(result))      .catch(error => console.error('Error:', error));    }  }}</script>

后端代码:

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestControllerpublic class BackendApplication {    public static void main(String[] args) {        SpringApplication.run(BackendApplication.class, args);    }    @PostMapping("/processArray")    public String processArray(@RequestBody String[] array) {        // 处理收到的数组        for (String element : array) {            System.out.println(element);        }        return "Array processed successfully";    }}

如果是python代码,也大同小异:

from flask import Flask, request, jsonifyapp = Flask(__name__)@app.route('/receiveArray', methods=['POST'])def receive_array():    received_array = request.json # 这里假设前端发送的是 JSON 数组    print(received_array) # 在后端打印接收到的数组    # 进行后续处理    return 'Array received successfully'if __name__ == '__main__':    app.run(debug=True)

4. 彩蛋

前端传输的有些普通数组,在前端传输过程中,对应的接口可以以toString格式传输给后端:
在这里插入图片描述

后端通过@RequestParam的注解接收

在这里插入图片描述

如果以JSON格式传输,则后端接口以@Requsetbody的注解接收
(除了上面的前端使用JSON.stringify()方法,也可在前端以JSONArray格式传输,后端以JSONArray的类型传输)


点击全文阅读


本文链接:http://zhangshiyu.com/post/97698.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1