Java解决跨域问题

package com.trs.gb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**

  • @author wuyc
  • 处理一些跨域问题
    */

@Configuration
public class CorsConfig {

@Bean
public WebMvcConfigurer corsConfigurer(){

   return new WebMvcConfigurer() {
       @Override
       public void addCorsMappings(CorsRegistry registry) {
           // 设置允许跨域的路由
           registry.addMapping("/**")
                   // 设置允许跨域请求的域名
                   .allowedOrigins("*")
                   // 再次加入前端Origin  localhost!=127.0.0.1
                   .allowedOrigins("http://localhost:63343")
                   // 是否允许证书(cookies)
                   .allowCredentials(true)
                   // 设置允许的方法
                   .allowedMethods("*")
                   //允许请求头
                   .allowedHeaders("*")
                   // 跨域允许时间
                   .maxAge(3600);
       }
   };

}
}


以下是AI建议的一些修改调整:
@Configuration
public class CorsConfig {

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    // 允许特定来源进行跨域请求
                    .allowedOrigins("https://www.trusted-website.com", "https://api.trusted-website.com") 
                    // 允许携带证书信息(cookies)
                    .allowCredentials(true) 
                    // 仅允许 GET 和 POST 请求
                    .allowedMethods("GET", "POST") 
                    // 仅允许指定的请求头
                    .allowedHeaders("Origin", "Accept", "Content-Type") 
                    // 跨域请求最大存活时间为3600秒(1小时)
                    .maxAge(3600); 
        }
    };
}

}


扫描二维码,在手机上阅读!

发表评论

电子邮件地址不会被公开。 必填项已用*标注