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



                                                                                                

  • 相关阅读:
    请简单介绍spring支持的常用数据库事务传播属性和事务隔离级别
    Spring Bean的作用域
    成员变量与局部变量的区别
    递归与迭代
    方法参数的传递机制 ---- 值传递
    windows phone 动画 当子控件超出父控件返回时
    把dataset 输出到 excel
    代码段
    c++ 学习纪录
    做自己的代码生成器
  • 原文地址:https://www.cnblogs.com/haciont/p/10784673.html
Copyright © 2020-2023  润新知