java架构师

java架构师

1、使用spring-boot设置跨域

package com.zb.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;

@Configuration
public class CorsConfig {
    public CorsConfig() {

    }

    @Bean
    public CorsFilter corsFilter() {
        // 1、添加cors配置信息
        CorsConfiguration config = new CorsConfiguration();

        // http://localhost:8080 为前端发起接口的域名
        config.addAllowedOrigin("http://localhost:8080");

        // 设置是否发送cookie信息
        config.setAllowCredentials(true);

        config.addAllowedMethod("*");

        config.addAllowedHeader("*");

        // 2、为url添加映射路径
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**", config);

        // 3、返回重新设定好的corsSource
        return new CorsFilter(corsSource);
    }
}

备注:

1、axios.defaults.withCredentials = true; 跨域的时候会带上cookies
2、config.setAllowCredentials(true); 发送cokies
但是我在测试的时候发现:axios没有设置withCredentials,也会出现cokkie;
config.setAllowCredentials(true)如果为false,会出现跨域情况

 2、字符串作为 URI 组件进行编码和解码

前端编码和解码:encodeURIComponent()和decodeURIComponent()

后端编码和解码:URLEncoder.encode()和URLDecoder.decode()