踩坑——纪实

1 npm安装

npm报错:request to https://registry.npm.taobao.org failed, reason certificate has expired

其实,早在2021年,淘宝就发文称,npm淘宝镜像已经从registry.npm.taobao.org切换到了registry.npmmirror.com。旧域名也将于2022年5月31日停止服务(不过,直到今天HTTPS证书到期才真正不能用了)

解决方案

1.1 查看当前的npm镜像设置

npm config list

1.2 清空缓存

npm cache clean --force

1.3 修改镜像

npm config set registry https://registry.npmmirror.com

1.4 查看修改结果

1.5 重新安装vue

npm install -g @vue/cli   #需要管理权限

vue3官网推荐在项目目录下执行:

npm create vue@latest

2 VScode——NPM脚本窗口找不到

设置UserExtensionsNpm→勾选Enable Run From Folder

点击项目右上角的...,勾选NPM Scripts

3 springboot项目中updateById()失效

在这里插入图片描述

实体类继承自公共实体类BaseEntity,并将主键id放进去了,service方法调用getById正常,但是调用updateById时,传入一个json实体却获取不到id,这时,在id上添加注解:@JsonProperty("id")

@JsonProperty(“id”) //入参转换,为解决前端传入的json包无法接收
@JsonFiels(name = “id”) //出参转换

4 前端跨域

http://127.0.0.1:8001/admin/edu/teacher/list/1/5’ from origin ‘http://localhost:9528’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

在这里插入图片描述

4.1 后端加个配置类

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 允许跨域的域名,*代表任何域名
                .allowedMethods("GET", "POST") // 允许的方法
                .allowedHeaders("*") // 允许任何请求头
                .allowCredentials(true) // 允许cookies
                /*.exposedHeaders(HttpHeaders.of("SET_COOKIE",fie))*/.maxAge(3600L);
    }
}

4.2 @CrossOrigin注解

也可以在Controller上添加该注解

5 路由出口

如果路由指向的页面组件是同一个,那么路由出口显示的页面组件不会重新渲染

为使重新渲染,需要为路由出口定义一个唯一key值

6 springdoc openapi3 swagger3文件上传

OpenAPI Specification - Version 3.1.0 | Swagger

#Considerations for File Uploads

In contrast with the 2.0 specification, input/output content in OpenAPI is described with the same semantics as any other schema type.file

In contrast with the 3.0 specification, the keyword has no effect on the content-encoding of the schema. JSON Schema offers a keyword, which may be used to specify the for the schema. The keyword supports all encodings defined in RFC4648, including “base64” and “base64url”, as well as “quoted-printable” from RFC2045. The encoding specified by the keyword is independent of an encoding specified by the header in the request or response or metadata of a multipart body – when both are present, the encoding specified in the is applied first and then the encoding specified in the header.format contentEncoding Content-Encoding contentEncoding contentEncoding Content-Type contentEncoding Content-Type

JSON Schema also offers a keyword. However, when the media type is already specified by the Media Type Object’s key, or by the field of an Encoding Object, the keyword SHALL be ignored if present.contentMediaType contentType contentMediaType

原来的写法:

public void upload(@RequestParam("file") MultipartFile file){}

3.0版本的写法:

public void upload(
    @RequestBody(
        content = @Content(
            mediaType = "multipart/form-data",
            schema = @Schema(type = "object"),
            schemaProperties = {
                @SchemaProperty(
                    name = "file",
                    schema = @Schema(
                        type = "string",
                        format = "binary"))
            }
        )
    ) MultipartFile file){}

7 连接mysql时出现[HY000][1130] null, message from server: “Host ‘‘ is not allowed报错

出现这个问题先考虑端口3306是否开通,如果开通还出现报错则开始下一步

解决这个问题有个很简单的方法就是先进入mysql然后命令

use mysql
update user set host='%' where user='root';

然后通过命令

GRANT ALL ON *.* TO 'root'@'%';
FLUSH PRIVILEGES;

8 Nacos2.2.3 启动成功但访问空白

修改conf/application.properties文件

### If turn on auth system:
nacos.core.auth.enabled=true

### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
### The two properties is the white list for auth and used by identity the request from other server.
#用户名
nacos.core.auth.server.identity.key=nacos
#密码
nacos.core.auth.server.identity.value=nacos

### The default token (Base64 String):
nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789

9 ERROR StatusLogger Log4j2 could not find a logging imple mentation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console…

添加依赖

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.23.1</version>
</dependency>

问题源自于easyexcel

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.4</version>
</dependency>

10 mapper.xml在pom文件中打包后找不到数据源配置了

mapper.xml文件在src/main/java/mapper/xml中,
在pom文件中添加了打包

<build>
    <!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

但是添加后,application.yml就变红了,运行报错

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

尝试把resoources下的application.yml也打包到maven里,成功了。

<build>
    <!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.yml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

看来maven默认是都打包,但是如果我自定义的话就要全都定义了。

11 Refused to execute script from because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled

每次打开前端,控制台都会报错,虽然不影响运行……

Refused to execute script from 'http://localhost:8080/something/index_bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

某度某应都试过了,无果。在StackOverflow搜索了下,方案:

Your webpack config is malformed. So your devServer is returning the fallback html file instead of the bundle.

Hence why the script is served with the (‘text/html’) MIME type.

devServer: {
    historyApiFallback:{
      index:'/dist/index.html'
    },
  }

You probably meant something like this:

devServer: {
  historyApiFallback: true
}

前端的工程只找到了webpack.dev.conf.js,果然有这一行,修改后,成功解决。

12 Nacos Whitelabel Error Page 503

Whitelabel Error Page

This application has no configured error view, so you are seeing this as a fallback.

Tue May 21 04:01:08 CST 2024

[9b38c884-1] There was an unexpected error (type=Service Unavailable, status=503).

用了负载均衡,控制台一路绿灯过去的,页面就是刷不出来,恼火。

查得,Nacos在2021版本起就删除了Ribbon的包,需要引入springcloud-loadbalancer

所以,依赖应该这么引:

<!-- nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!-- loadbalancer -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

13 Mybatis-Plus代码生成器

Spring Boot (v3.2.5)
mybatis-plus-generator (v3.5.6)

Mybatis-Plus代码生成器配置

14 @RequestBody

如果是来自springframework的注解,则会根据定义自动封装为Entity,

但如果是swagger的注解,没有传的参数就会自动填充为空。

比如User类的主键id设置了自增,前端传入的json中没有id值,如果是第一种,会自动封装;如果是第二种,数据库语句报错。

15 maven install jar后没有将包加载到本地仓库

执行的命令是:

mvn install:install-file  -DgroupId=com.aliyun  -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.15 -Dpackaging=jar  -Dfile=aliyun-java-vod-upload-1.4.15.jar

也成功了,但pom中引入依赖还是爆红。

尝试绝对路径、修改install-plugins依然无果。

后发现它是安装的路径不对。

在maven目录下的/conf/settings.xml中有一行是专门定义本地仓库路径的

<!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

<localRepository>D:\Mavens\repository</localRepository>

而我定义的路径是maven目录下新建的repository文件夹。

改过来即可:

<localRepository>D:\DevelopEnvironments\Mavens\repository</localRepository>

16 MyBatis-Plus代码生成器springboot的测试类运行报错

Java HotSpot™ 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended

解决方案:debugging - Java HotSpot™ 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended - Stack Overflow

在IntelliJ的当前测试类项目中,
Run/Debug Configurations→左下角Edit configuration templateModify options→勾选Add VM options

在多出来的输入框中填写

-Xshare:off

确认即可。

17 解决日期转换异常 JSON parse error: Cannot deserialize value of type java.util.Date from String

  • Entity

    public class BaseEntity implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Schema(description = "讲师ID")
        @TableId(value = "id", type = IdType.ASSIGN_ID)
        private String id;
        @Schema(description = "创建时间", example = "2099-01-01 8:00:00")
        @TableField(fill = FieldFill.INSERT) // 这里只是通过MyBatis-Plus指定了什么时候填充,但是没有告诉程序如何填充
        private Date gmtCreate;
    
        @Schema(description = "更新时间", example = "2099-01-01 8:00:00")
        @TableField(fill = FieldFill.INSERT_UPDATE) // 这里只是通过MyBatis-Plus指定了什么时候填充,但是没有告诉程序如何填充
        private Date gmtModified;
    }
    
  • Controller

    @Operation(description = "将信息缓存到redis中")
    @PostMapping("save-test")
    public R saveAd(@RequestBody MyInfo info){
        redisTemplate.opsForValue().set("info", info);
        return R.ok();
    }
    
  • Swagger测试

    #传入的数据
    {
      "id": "string",
      "gmtCreate": "2099-01-31T21:41:38.647Z",
      "gmtModified": "2099-01-31T21:41:38.647Z"
    }
    
  • 报错

    JSON parse error: Cannot deserialize value of type `java.util.Date` from String
    
  • 解决方案

    在对应的日期属性上添加注解@JsonFormat

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd") //后端传入前端的日期格式化
    

18 MySql连接报错The driver has not received any packets from the server.

检查mysql版本和项目依赖中mysql-connector-j.version

19 Springboot test报错java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test

原因是把代码生成器测试类写在了test/java路径下,应该在测试类上加一个包名,而且要与main/java下要生成的包名相同

20 seata启动错误

org.yaml.snakeyaml.scanner.ScannerException: mapping values are not allowed here in ‘reader’, line 50, column 11:
nacos:
^
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchValue(ScannerImpl.java:902)

yml文件语法要求严格,仔细检查下缩进,空格等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值