javascript - CORS blocked - Spring Boot and React
问题描述
I have my Spring Boot REST API. Link: "http://localhost:8080/api/components/component/list"
For the frontend, I am using React, above is the link that I want the React Admin app to consume.
Here is my Spring Boot's CORS Code, it is in a separate class called CorsConfig:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry myCorsRegistry){
myCorsRegistry.addMapping("/**")
.allowedOrigins("http://localhost:3000") //frontend's link
.allowedHeaders("*")
.allowedMethods("*")
.allowCredentials(true)
.maxAge(4800);
}
}
I also tried this, but it still does not work:
@Configuration
public class CorsConfig{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
};
}
}
For my controller class I have the following:
@CrossOrigin
@RequestMapping("/api/components/component")
@RestController
public class Component{
@Autowired
//code...
}
Here is my React Code:
const parentURL =
restProvider(`http://localhost:8080/api/components/component`);
function App() {
return(
<Admin dataProvider={parentURL}>
<Resource name="list" list={ListGuesser} />
</Admin>
);
}
Here is the error I am getting in my Chrome console:
Access to fetch at 'http://localhost:8080/api/components/component/DashBoard?
filter=%7B%7D&range=%5B0%2C9%5D&sort=%5B%22id%22%2C%22ASC%22%5D' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
My Question: How to fix the above error ?
解决方案
尝试在控制器顶部添加 @CrossOrigin(origins ="http://localhost:3000") 。它应该工作。
推荐阅读
- javascript - 这个语法错误是什么意思?
- authentication - 使用 Session() 冻结登录
- tensorflow - 当我尝试加载使用 PReLU 作为激活函数的训练模型时出现“ValueError:未知激活函数:PReLU”?
- android - 我在哪里对 android studio 上的华为应用内购买进行编码以及如何将我的应用与 IAP 链接
- kubernetes - 如何为 Kubernetes 集群启用 RequestedToCapacityRatio 功能(1.18 版)
- x11 - 如何为深度= 32的窗口设置不透明背景
- javascript - 提交表单后,如何在html中的表单的同一页面打印user_input?
- javascript - 获取具有自己价值和子价值的对象的正确方法
- image - 神经网络如何看到 csv 形式的图像?
- mongodb - 使用 `brew services` 时运行 `mongo` 会产生 `Operation timed out`