1.全局配置java
在application.java文件添加CorsRegistry配置web
package com.ypnh.authority; import com.ypnh.authority.infrastructure.config.Config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @EnableConfigurationProperties({Config.class}) @EnableEurekaClient @EnableFeignClients @SpringBootApplication public class AuthorityCenterApplication { public static void main(String[] args) { SpringApplication.run(AuthorityCenterApplication.class, args); } //全局配置跨域 @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/users/*").allowedOrigins("http://localhost:9527"); } }; } }
2.局部配置spring
在具體方法添加@CrossOrigin(origins = 「http://localhost:9527」)註解 json
@ApiOperation(value = "查詢用戶")
@CrossOrigin(origins = "http://localhost:9527") @PostMapping(value = "/users", produces = "application/json;charset=UTF-8") public List<User> findAllUsers() { List<User> users = userService.findAll(); return users; }