前后端传参中遇见的问题

前后端传参经常容易出错,本文记录开发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

重启项目,运行成功!

相关推荐
很晚很晚了11 分钟前
纯前端转全栈 Day 1:我从第一个 NestJS 接口开始
前端
Lee川1 小时前
从零解剖一个 AI Agent Tool是如何实现的
前端·人工智能·后端
wangruofeng2 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
2401_833269303 小时前
Java网络编程入门
java·开发语言
金銀銅鐵3 小时前
[Java] 如何将 Lambda 表达式对应的类保存到 class 文件中?
java·后端
それども4 小时前
Gradle 构建疑难杂症 Could not find netty-transport-native-epoll-linux-aarch_64.ja
java·服务器·gradle·maven
正儿八经的少年4 小时前
application.yml 系列配置文件作用与区别
java·配置文件
李白的天不白4 小时前
SSR服务端渲染
前端
鱼很腾apoc4 小时前
【学习篇】第20期 超详解 C++ 多态:从语法规则到底层原理
java·c语言·开发语言·c++·学习·算法·青少年编程
cheems95275 小时前
[Spring MVC] 统一功能与拦截器实践总结
java·spring·mvc