前后端传参中遇见的问题

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

重启项目,运行成功!

相关推荐
智码看视界25 分钟前
老梁聊全栈系列:(阶段一)架构思维与全局观
java·javascript·架构
黎宇幻生27 分钟前
Java全栈学习笔记33
java·笔记·学习
小周同学@2 小时前
谈谈对this的理解
开发语言·前端·javascript
Wiktok2 小时前
Pyside6加载本地html文件并实现与Javascript进行通信
前端·javascript·html·pyside6
@AfeiyuO2 小时前
分类别柱状图(Vue3)
typescript·vue·echarts
一只小风华~2 小时前
Vue:条件渲染 (Conditional Rendering)
前端·javascript·vue.js·typescript·前端框架
柯南二号2 小时前
【大前端】前端生成二维码
前端·二维码
2501_915918412 小时前
HTTPS 端口号详解 443 端口作用、iOS 抓包方法、常见 HTTPS 抓包工具与网络调试实践
android·网络·ios·小程序·https·uni-app·iphone
程序员码歌2 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
BillKu3 小时前
推荐 Eclipse Temurin 的 OpenJDK
java·ide·eclipse