来源已被 CORS 政策 Spring boot 和 React 阻止

IT技术 reactjs spring-boot controller cors-anywhere
2021-05-09 18:23:37

带有 React 的 Spring Boot

CORS 策略已阻止从源“ http://localhost:3000访问“ http://localhost:8080/处的 XMLHttpRequest

这是一个返回所有区对象的控制器

CORS 策略已阻止在 ' http://localhost:8080/从源 ' http://localhost:3000 '访问 XMLHttpRequest 请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

package com.ministry.demo.controller;

import com.ministry.demo.model.District;
import com.ministry.demo.repository.DistrictRepository;
import com.ministry.demo.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = "district")
public class DistrictController {
    @Autowired
    DistrictService service;

    @GetMapping(path = "getAll")
    List<District> getAllDistrict(){
        return service.getAllDistricts();
    }
}
4个回答

我找到了答案

package com.ministry.demo.controller;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping(path = "district")
public class DistrictController {
    @Autowired
    DistrictService service;

    @GetMapping(path = "getAll")
    List<District> getAllDistrict(){
        return service.getAllDistricts();
    }
}

我的配置文件

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*");
    }

}

找到了一个对我有用的替代答案。

@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and().httpBasic();
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

如果您的后端和您的应用程序不在同一地址上运行,您的浏览器通常不允许您调用后端。这旨在成为一项安全功能。

要允许您的浏览器调用您的 api,请将 Access-Control-**** 标头添加到您的后端响应(从 Spring 响应时)。

请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

允许所有来源的最基本的标题:

Access-Control-Allow-Origin: *

这是在 Spring 中添加这些标头的教程:https : //spring.io/guides/gs/rest-service-cors/