reactjs CORS策略Sping Boot 和React已阻止始发

4dbbbstv  于 2022-12-29  发布在  React
关注(0)|答案(5)|浏览(152)

ReactSpring Boot

CORS策略已阻止从源"http://localhost:3000"访问位于"http://localhost:8080/"的XMLHttpRequest:

    • 这是返回所有地区对象的控制器**

CORS策略已阻止从源"http://localhost:3000"访问"http://localhost:8080/"处的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();
    }
}
lf5gs5x2

lf5gs5x21#

"我找到了答案"

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();
    }
}
5gfr0r5j

5gfr0r5j2#

我的配置.java

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

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

}
4zcjmb1e

4zcjmb1e3#

找到了另一个对我有效的答案。

@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;
    }
}
x6492ojm

x6492ojm4#

如果您的后端和应用程序不在同一个地址上运行,您的浏览器通常不允许您调用后端。这是一项安全功能。
为了允许浏览器调用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/

k2arahey

k2arahey5#

问题出在我的springboot后端,因为我没有添加一些控制头,我已经在我的springboot API中添加了一些访问控制头来修正这个错误。
错误:网络::错误失败200
前端:React
后端:Springboot API[JWT]

React:

const LOGIN_URL = "http://localhost:8080/api/login";
      const params = new URLSearchParams()
      params.append('email', email)
      params.append('password',password)
    
      const response = await axios.post(LOGIN_URL, params);

Spring启动/java:

@Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication){
       ...
       response.setHeader("Access-Control-Allow-Origin", "*");
       response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
       response.setHeader("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
       ...
    }

相关问题