【问题标题】:@CrossOrigin(origins = { "*" }) not working for Springboot + React app@CrossOrigin(origins = { "*" }) 不适用于 Springboot + React 应用程序
【发布时间】:2021-11-19 17:04:32
【问题描述】:

我有一个 Springboot 后端和一个 React 前端,直到今天,它们都运行良好。我能够发送和接收请求/响应。其他 StackOverflow 问题/答案都只需添加 @CrossOrigin(origins = { "*" }) 但这对我不起作用。

现在,突然间,我收到错误消息:

Access to XMLHttpRequest at 'http://localhost:8080/api/employees' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是,据我所知,我确实设置了 CORS。就像我说的那样,它正在工作,但现在即使我没有更改 CORS 起源,它也不能正常工作。

这就是我在 Springboot 后端拥有的:

@CrossOrigin(origins = { "*" })
@RestController
@RequestMapping("/api/")
public class EmployeeController {

    // Auto-inject EmployeeServices Class into this class so we can use the object
    // without calling 'new EmployeeServices'
    @Autowired
    private EmployeeServices employeeServices;

    // GET all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeServices.getAllEmployees();
    }
}

自上次工作以来我所做的唯一一件事就是添加要求将 JsonWebToken 作为所有请求的header。这适用于邮递员:

我尝试将硬编码的 JWT 添加到我的 axios 请求中,以防 JWT 是给我CORS 错误的原因:

class EmployeeService {
  getEmployees() {
    console.log("getting employees!");
    console.log("Environment variable: " + process.env.NODE_ENV);

    let config = {
      headers: {
        Authorization:
          "Bearer " +
          "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb28iLCJleHAiOjE2MzI3ODgwNzgsImlhdCI6MTYzMjc1MjA3OH0.ynUaU9IR893O7uaEjaQ6xPSQh9dEIWdU0DYwwRfXHHM",
      },
    };
    return axios
      .get(API_BASE_URL + "employees", null, config)
      .then(console.log("did it!"));
  }
}

但是当我访问网页并让 React 发出请求时,我收到了 CORS 错误。到底是怎么回事? * 不应该启用所有来源吗?我需要在前端列出什​​么来完成这项工作吗?

谢谢!

【问题讨论】:

    标签: java reactjs spring-boot spring-security cors


    【解决方案1】:

    这是我用的:

    @Bean
    public CorsConfigurationSource corsConfiguration() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.applyPermitDefaultValues();
        corsConfig.addAllowedOrigin("http://localhost:3000");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
        return source;
    }
    

    也许您只需要更改为"/**",但至少这应该让您开始。

    编辑:完整示例可能会有所帮助Spring Webflux JWT Security Demo

    【讨论】:

    • 这个去哪儿了?什么文件?
    • 我把它放在@Configuration 但我认为任何地方都可以注册一个bean。
    • nvm 看起来很有效。但是我必须更改我的config 函数才能拥有这一行` http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues()); ` 但是现在 jwt 不工作了
    • 嗯,很高兴你让它工作了。我不必向 HttpSecurity 添加任何 cors 配置,但它确实有一个 crsf().disable()。我不认为这有关系。当您构建您的应用程序并从同一来源的服务器/服务静态提供它时,这些问题“消失”了,所以我没有花很多精力来理解这一点。
    猜你喜欢
    • 2018-03-16
    • 2020-04-24
    • 2023-03-26
    • 1970-01-01
    • 2021-11-04
    • 2021-07-13
    • 2023-03-10
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多