由前端向后端发送一个json键值对
<template>
<div>
<button @click="sendRequest">发送请求button>
div>
template>
<script setup>
import axios from 'axios';
const sendRequest = () => {
const jsonData = {
key1: 'value1',
key2: 'value2',
};
const jsonString = JSON.stringify(jsonData);
axios.post('http://localhost:8080/test', jsonString, {
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('成功发送请求', response);
})
.catch(error => {
console.error('发送请求失败', error);
});
};
script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
package com.example.myjson;
import org.springframework.web.bind.annotation.*;
@CrossOrigin
@RestController
public class JSONController {
@PostMapping("/test")
public String handleJSONRequest(@RequestBody String jsonString) {
System.out.println("接收到的JSON字符串:" + jsonString);
return "成功接收到JSON请求";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
发送一个由前端json包装过的类对象
<template>
<div>
<button @click="sendTaskInfo">发送TaskInfobutton>
div>
template>
<script setup>
import axios from 'axios';
const sendTaskInfo = () => {
const taskInfo = {
id: 1,
task: '完成项目任务',
startTime: new Date(),
endTime: new Date(),
elapsedTime: 3600,
};
const jsonTaskInfo = JSON.stringify(taskInfo);
axios.post('http://localhost:8080/test', jsonTaskInfo, {
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('成功发送 TaskInfo', response);
})
.catch(error => {
console.error('发送 TaskInfo 失败', error);
});
};
script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
public class TaskInfo {
private int id;
private String task;
private Date startTime;
private Date endTime;
private long elapsedTime;
}
@PostMapping("/test")
public ResponseEntity<String> handleJSONRequest(@RequestBody TaskInfo taskInfoJson) {
System.out.println("接收到的 TaskInfo 对象:" + taskInfoJson);
return new ResponseEntity<>("成功接收到 TaskInfo 对象", HttpStatus.OK);
}