前言
通過問題Bug指引代碼實戰(zhàn),結合實戰(zhàn)問題,相應查漏補缺
1. 問題所示
前端傳輸數組給后端的時候,出現如下問題:
前端log請求如下:
且請求后端你的時候出現了服務器500error:
2. 普通數組
如果不使用 JSON 格式傳輸數據,而是使用普通的數組,可以考慮通過 POST 請求的 body 直接傳輸數組的形式
- 前端,可以將數組直接作為請求的 body
- 后端,可以直接接收請求的 body 作為數組進行處理
前端數據:
<template>
<div>
<!-- 按鈕觸發(fā)事件 -->
<button @click="sendArrayToBackend">發(fā)送數組到后端</button>
</div>
</template>
<script>
export default {
methods: {
sendArrayToBackend() {
const array = ['a', 'b', 'c'];
// 發(fā)送數組到后端
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 直接發(fā)送到后端的 /processArray
接口。后端接收到字符串后,根據逗號分隔拆分成數組進行處理
3. JSON格式
前端通過點擊按鈕觸發(fā)sendArrayToBackend
方法,該方法使用Fetch API將數組發(fā)送到后端的/processArray接口。后端接收到數組后進行處理,并返回響應。
前端代碼:
<template>
<div>
<!-- 按鈕觸發(fā)事件 -->
<button @click="sendArrayToBackend">發(fā)送數組到后端</button>
</div>
</template>
<script>
export default {
methods: {
sendArrayToBackend() {
const array = ['a', 'b', 'c'];
// 發(fā)送數組到后端
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 # 這里假設前端發(fā)送的是 JSON 數組
print(received_array) # 在后端打印接收到的數組
# 進行后續(xù)處理
return 'Array received successfully'
if __name__ == '__main__':
app.run(debug=True)
4. 彩蛋
前端傳輸的有些普通數組,在前端傳輸過程中,對應的接口可以以toString格式傳輸給后端:
后端通過@RequestParam
的注解接收
文章來源:http://www.zghlxwxcb.cn/news/detail-854138.html
如果以JSON格式傳輸,則后端接口以@Requsetbody
的注解接收
(除了上面的前端使用JSON.stringify()
方法,也可在前端以JSONArray
格式傳輸,后端以JSONArray
的類型傳輸)文章來源地址http://www.zghlxwxcb.cn/news/detail-854138.html
到了這里,關于前端傳輸數組類型到后端(附代碼)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!