Spring Boot CORS策略已阻止从源“http://localhost:4200”访问位于“http://localhost:8090/xxx”的XMLHttpRequest

83qze16e  于 2023-02-08  发布在  Spring
关注(0)|答案(1)|浏览(131)

我在从angular向java spring-boot项目发送注册信息时遇到错误。我尝试了数千种方法来解决它,但都是徒劳的。无法找出阻止java项目接受请求的原因。控制台中的错误:
CORS策略已阻止从源“http://localhost:4200”访问位于“http://localhost:8090/bites/service/signup”的XMLHttpRequest:印前检查响应中的Access-Control-Allow-Headers不允许使用请求标头字段域。
下面是我的java代码:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        try {
            System.out.println("inside filter>>>>");
             HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request = (HttpServletRequest) req;
                response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Methods",
                        "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");

            chain.doFilter(request, response);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }

我知道角注册表是发送准确的请求与凭据的java项目,但在java方面的请求被拒绝。
寻求帮助。
我正在尝试我的java应用程序接受来自Angular 项目的请求

s3fp2yjn

s3fp2yjn1#

您能否添加配置:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
            }
        };
    }
}

相关问题