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

前言

通过问题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
@RestController
public 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
@RestController
public 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, jsonify

app = 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的类型传输)

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值