1. @CrossOrigin annotation solves cross domain
@CrossOrigin(origins = "http://api.gmall.com:8888") // The version of spring must be above 4.2 to achieve cross-domain
If you are also using the spring framework, and the version is above 4.2, you can use the @CrossOrigin annotation, and
the url in the brackets can be replaced with ""*"". If there are multiple methods in this controller, the annotation can be written directly in the class top.
@RestController
@CrossOrigin(origins = "http://api.gmall.com:8888") // 实现跨域 要求spring的版本必须4.2以上
@RequestMapping("/admin/product")
public class ManagerController {
@Autowired
ManagerService managerService;
@GetMapping("/getCategory1")
public Result getCategory1(){
List<BaseCategory1> category1List = managerService.getCategory1();
return Result.ok(category1List);
// return Result.build(category1List, ResultCodeEnum.SUCCESS);
}
}
2. Write on the class
//写在类上,不用每个方法都写这个注解了
@CrossOrigin(origins="*",maxAge=3600)
@RestController
public class LoginController {
}
3. 1 Configuration class
package com.kd.gmall.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
// cors跨域配置对象
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
configuration.setAllowCredentials(true);
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
// 配置源对象
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**", configuration);
// cors过滤器对象
return new CorsWebFilter(configurationSource);
}
}
3.2 application.yml
server:
port: 80
spring:
application:
name: api-gateway
cloud:
nacos:
discovery:
server-addr: 192.168.200.128:8848
gateway:
discovery: #是否与服务发现组件进行结合,通过 serviceId(必须设置成大写) 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
locator: #路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。
enabled: true
routes:
- id: service-product
uri: lb://service-product
predicates:
- Path=/*/product/** # 路径匹配