【问题标题】:Getting problem in enabling cross origin for spring boot backend and react frontend在为 Spring Boot 后端启用跨源和响应前端时遇到问题
【发布时间】:2020-11-14 18:00:40
【问题描述】:

我已经创建了 react frotend 并创建了 spring boot 后端,但它给出了错误

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

反应代码:

    import axios from "axios"

class Helloworldservice{
    executehelloworldservice(){
        return axios.get('http://localhost:8080/home');
    }

}
export default new Helloworldservice()

启动代码:

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class RestServiceController {

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public User giveServiceBack() {
        return new User(1, "satyajit");
    }

}

还单独添加了配置

@Configuration
@EnableWebMvc
public class Webconfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
    enter code here

}

这些都不能解决我的问题。

【问题讨论】:

    标签: reactjs spring-boot rest


    【解决方案1】:

    尝试添加allowedHeadersallowCredentials

    @RestController
    @CrossOrigin(origins = "http://localhost:4200",allowedHeaders = "*", allowCredentials = "true")
    public class RestServiceController {
    
        @RequestMapping(value = "/home", method = RequestMethod.GET)
        public User giveServiceBack() {
            return new User(1, "satyajit");
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2018-11-14
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多