首页 > 解决方案 > React-Spring Boot Web APP 的 CORS 问题

问题描述

我是 webdev 领域的新手,我正在尝试开发这个非常简单的应用程序,您可以在其中购买足球比赛的门票。该程序运行得很好,但我只是尝试创建一个购物车,我的想法是每次有人向购物车添加一个名为 Paid 的属性时将其推送到数据库中,该属性将是 0(未付费)或 1(付费,结帐后)。这一切都很好,但是当我完成所有设置时,我看到呼叫被 CORS 阻止了,这很奇怪,因为我已经设置了 CORS 的所有内容。这是我认为相关的代码片段:

我的 API 中的控制器(除 getTicketByFanId() 外,每个调用都有效)

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(path="/api/v1/ticket")
public class TicketController {
    @Autowired
    private TicketRepository repository;

    @GetMapping("/fan/{id}/{paid}")
    public @ResponseBody Iterable<Ticket> getTicketByFanId(@PathVariable int id, @PathVariable int paid) {
        return repository.findByFanIDAndPaid(id, paid);
    }

    @PostMapping
    public @ResponseBody String addNewTicket (@RequestBody Ticket ticket) {
        repository.save(ticket);
        return "Saved";
    }

    @GetMapping
    public @ResponseBody Iterable<Ticket> getAllTickets() {
        return repository.findAll();
    }

这是我为 WebSecurityConfig 设置的:

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/auth/**").permitAll()
                .antMatchers("/api/test/**").permitAll()
                .antMatchers("/api/v1/**").permitAll()
                .anyRequest().authenticated();


        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

我当然已经研究了很长一段时间,并尝试了我在几个论坛(包括 stackoverflow)上看到的大部分内容,但似乎没有一个添加可以解决这个问题。我几乎可以肯定问题来自我从路径中获取变量的事实,因此我还尝试以不同的方式编辑我的配置方法,这是解决其余方法的 CORS 问题的方法。除其他外,我尝试添加这样的代码行:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:3000/")
                        .allowedMethods("PUT", "DELETE", "GET")
                        .allowedHeaders("header1", "header2", "header3")
                        .exposedHeaders("header1", "header2")
                        .allowCredentials(false).maxAge(3600);
            }
        };
    }

我得到的最大结果是如果我只是尝试允许所有内容但仍然没有修复,则将 CORS 错误更改为 404...

关于我的前端,如前所述,我正在使用 React,并且我正在通过 AXIOS 进行 API 调用。这是我正在打的电话:

(TICKET_API_BASE_URL = http://localhost:8080/api/v1/ticket)
getUnpaidTickets(fanID){
        return axios.get(TICKET_API_BASE_URL + "/" + fanID + "/0");
    }

将其添加到该州的数组中,然后映射到站点中,这就是我到目前为止一直在做的事情,并且效果很好。

这是我每次尝试加载页面时收到的错误截图:

1

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

xhr.js:177 GET http://localhost:8080/api/v1/ticket/2/0 net::ERR_FAILED

createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

预先感谢任何试图帮助我的人!

标签: javareactjsaxios

解决方案


当您收到404错误代码时,它表明 CORS 工作正常。

您收到404错误是因为您使用 axios 请求以下 URL:

http://localhost:8080/api/v1/ticket/2/0

但是你@GetMapping的配置是这样的:

@GetMapping("/fan/{id}/{paid}")

请注意/fan路径的不同。

将 axios URL 更改为:

http://localhost:8080/api/v1/ticket/fan/2/0

或者你的控制器映射:

@GetMapping("/{id}/{paid}")

推荐阅读