Vue应用请求SpringBoot API出现 CORS 跨域请求设置 Invalid CORS request错误

1.全局配置

在application.java文件添加CorsRegistry配置

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.局部配置

在具体方法添加@CrossOrigin(origins = “http://localhost:9527”)注解  

@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;
}

 



                                                                                            

posted @ 2019-04-28 16:22  haxnt  阅读(16770)  评论(0编辑  收藏  举报