在我的社区项目开发环境中,我有一个功能是需要使用复选框选中一组值,去放到后端MySQL的中间表中,还需要这一组复选框所属的主键作为多对多关系映射,所以就涉及到了需要将一个字符串和一个数组传送到后端
以下是我社区项目相关的源代码:
后端API:
/**
* @author LiYuan
* @version v1.0.0.20240819_base
* @date 2024/08/19 15:56
* @description 推荐歌单和歌曲中间表接口
*/
@RestController
@RequestMapping("/music/v1/song-sheet-song")
public class MusicSongSheetSongController {
@Resource
private MusicSongSheetSongService musicSongSheetSongService;
@PostMapping("/save/{songSheetId}")
public ResponseResult<String> saveSongSheetSong(
@PathVariable("songSheetId") String songSheetId,
@Valid @RequestBody List<String> songIds) {
return musicSongSheetSongService.saveSongSheetSong(songSheetId, songIds);
}
}
前端请求API:
api.ts
import request from '@/utils/request'
import type { singerFormType, songInfoFormType } from '@/types/global.d'
const BASE_MUSIC_PREFIX = '/music/v1/'
export function postSongSheetSongAdd(songSheetId: string, params: string[]) {
return request({
url: BASE_MUSIC_PREFIX + 'song-sheet-song/save/' + songSheetId,
method: 'post',
data: { params }
})
}
TempView.vue
import { ref, onMounted } from 'vue';
import { useMusicStore } from '@/stores/pinia/music';
const checkList = ref<string[]>([])
const submitForm = async () => {
console.log(checkList.value)
const result: AxiosResponse<ResponseResult<string>, AxiosRequestConfig> = await postSongSheetSongAdd(useMusicStore().editNowSongSheetId, checkList.value)
if (result.code === 20000) {
ElMessage.success(result.data)
songListTable()
dialogFormVisible.value = false
} else {
ElMessage.error(result.message)
dialogFormVisible.value = false
}
}
本来是这么写的,测试环境一发请求报错如下:
通过全局异常处理器可以看到报了个什么JSON parse error:
信息:
JSON parse error: Cannot deserialize value of type `java.util.ArrayList<java.lang.String>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<java.lang.String>` from Object value (token `JsonToken.START_OBJECT`)
at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]
哎呀,这可解决了我整整10天的时间啊,翻阅大量资料以及使用AI后才知道,我的前端请求API的data的数据形式写错了,我写的是对象写法,改为数组写法就好了,也就是去掉那个 {}
import request from '@/utils/request'
import type { singerFormType, songInfoFormType } from '@/types/global.d'
const BASE_MUSIC_PREFIX = '/music/v1/'
export function postSongSheetSongAdd(songSheetId: string, params: string[]) {
return request({
url: BASE_MUSIC_PREFIX + 'song-sheet-song/save/' + songSheetId,
method: 'post',
// 去掉这个 {} ,变为数组参数的形式
data: params
})
}
记录一下这个小坑