Vue.js向SpringBoot发送数据异常:接收内容与发送不一致求助
解决Vue.js向SpringBoot发送数据后内容不一致的问题
问题场景
你通过Vue.js的axios发送字符串file14/04/2023到SpringBoot接口,后端收到的却是file14%2F04%2F2023=,与原内容不符。
问题原因
- 你手动调用
encodeURIComponent对字符串编码,导致斜杠被转义为%2F; - axios直接传递字符串时,默认会将其当作
application/x-www-form-urlencoded格式的请求体,解析为key=的形式(编码后的字符串被当作key,value为空),因此后端收到带=的内容。
解决方案
方案一:按JSON格式发送原始字符串
无需手动编码,让axios以JSON格式发送原始内容,SpringBoot的@RequestBody会自动解析出正确内容。
修改Vue.js代码:
axios .post('http://localhost:8080/apii/Recevoir', this.NonFichier, { headers: { 'Content-Type': 'application/json' } }) .then((response) => { console.log(response.data) }) .catch((error) => { console.log(error) })
SpringBoot代码保持不变:
@PostMapping(value = "/Recevoir", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> recevoir(@RequestBody String message) { System.out.println("Le message reçu est : " + message); return ResponseEntity.ok("String reçu avec succès ! et la donner recu est : " + message); }
方案二:按表单格式发送键值对
如果需要使用application/x-www-form-urlencoded格式,正确构造键值对后发送,axios会自动处理编码,SpringBoot用@RequestParam接收。
修改Vue.js代码:
const formData = new URLSearchParams(); formData.append('message', this.NonFichier); axios .post('http://localhost:8080/apii/Recevoir', formData) .then((response) => { console.log(response.data) }) .catch((error) => { console.log(error) })
修改SpringBoot代码:
@PostMapping(value = "/Recevoir", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> recevoir(@RequestParam String message) { System.out.println("Le message reçu est : " + message); return ResponseEntity.ok("String reçu avec succès ! et la donner recu est : " + message); }
内容的提问来源于stack exchange,提问作者Mass Mak
相关产品推荐
相关产品推荐

