我有我的SpringBootRESTAPI。链接:“http://localhost:8080/api/组件/组件/列表“
对于前端,我使用的是react,上面是我希望react管理应用程序使用的链接。
这是我的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.
我的问题是:如何修复上述错误?
暂无答案!
目前还没有任何答案,快来回答吧!