【发布时间】:2021-07-03 17:36:27
【问题描述】:
我有我的 Spring Boot REST API。链接:“http://localhost:8080/api/components/component/list”
对于前端,我使用的是 React,上面是我希望 React Admin 应用使用的链接。
这是我的 Spring Boot 的 CORS 代码,它位于一个名为 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);
}
}
我也试过了,还是不行:
@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);
}
};
}
}
对于我的控制器类,我有以下内容:
@CrossOrigin
@RequestMapping("/api/components/component")
@RestController
public class Component{
@Autowired
//code...
}
这是我的反应代码:
const parentURL =
restProvider(`http://localhost:8080/api/components/component`);
function App() {
return(
<Admin dataProvider={parentURL}>
<Resource name="list" list={ListGuesser} />
</Admin>
);
}
这是我在 Chrome 控制台中遇到的错误:
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.
我的问题: 如何解决上述错误?
【问题讨论】:
-
试试
allowedOrigins("*"),如果可行请告诉我 -
在控制器中添加@CrossOrigin 注释时,尝试在那里指定原点。它应该工作。
@CrossOrigin(origins = "*") -
sai manoj:您是在内置 tomcat 服务器中运行 sprint 启动应用程序,还是在 tomcat 或任何其他服务器中部署 jar 或 war 文件?
标签: javascript java reactjs spring spring-boot