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

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

9 人参与  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://m.zhangshiyu.com/post/97698.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

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

最新文章

  • [被CBA开除后,我成了NBA新贵]小说无删减版在线免费阅读_[顾白梅根·福克斯]全文免费无弹窗阅读_笔趣阁
  • 陆司沉沐星澜结局+番外榜单_陆司沉沐星澜结局+番外榜单
  • 完结文爱似流萤遇繁星结局+番外高口碑列表_完结文爱似流萤遇繁星结局+番外高口碑(沐星澜陆司沉)
  • [重生70后兼祧两房的父亲悔疯了]小说精彩节选推荐_妹妹熊孩子姜霞小说节选免费试读
  • 你是我未拆的遗书(桑年裴谨言)_你是我未拆的遗书桑年裴谨言
  • 她在春日里沉眠下载乔清瑜季泽珩完本_她在春日里沉眠下载(乔清瑜季泽珩)
  • 桑年与裴谨言的+后续+结局(桑年裴谨言)列表_桑年与裴谨言的+后续+结局(桑年裴谨言)桑年与裴谨言的+后续+结局在线
  • [替妹妹受电刑五年后,全家逼我让出老公]全角色番外合集包_[沈雪妹妹陆宴州]情感冲突名场面试读章
  • 你是我未拆的遗书结局+番外纯净版(桑年裴谨言)全书浏览_你是我未拆的遗书结局+番外纯净版全书浏览
  • 傅沉砚沈昭宜(填我十万八千梦全书+后续+结局)_(傅沉砚沈昭宜)列表_笔趣阁(填我十万八千梦全书+后续+结局)
  • 老婆拍卖新婚夜后,她后悔了全章节免费阅读_[苏雨禾宋易秦硕]角色专属支线试读入口
  • 你是我未拆的遗书结局+番外+后续看点十足(裴谨言桑年)_你是我未拆的遗书结局+番外+后续看点十足(裴谨言桑年)裴谨言桑年免费列表_笔趣阁(裴谨言桑年)

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

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