前后端传参中遇见的问题

前后端传参经常容易出错,本文记录开发springBoot+Mybatis-plus+vuecli项目中出现的传参问题及解决办法

1.前后端没有跨域配置,报错

解决方法:后端进行跨域配置,拷贝CorsConfig类

java 复制代码
package com.example.xxxx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局配置可跨域访问api接口
 */

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); //允许任何域名
        corsConfiguration.addAllowedHeader("*"); //允许任何头
        corsConfiguration.addAllowedMethod("*"); //允许任何方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); //注册
        return new CorsFilter(source);
    }
}

2.longtext类型 前端json内容包含转义字符,报错

WARN 9296 --- [nio-8090-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 2, column: 15] (through reference chain: com.example.memo.entity.Note["content"])]

出现原因:Json 字符中有有些字段比如空格、反斜杠、换行符等一些特殊字符,但是 Json 框架没有对这些字符进行处理,就会导致出现错误。

解决方法:加入 fastjson 依赖

html 复制代码
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

在配置文件中加入

java 复制代码
spring:
	jackson:
	    parser:
	      allow-unquoted-control-chars: true

重启项目,运行成功!

相关推荐
大怪v4 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习4 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
皮皮林5514 小时前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
小兵张健4 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒7 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat7 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
代码老中医7 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
不会敲代码17 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫7 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川7 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能