是的,我知道有数以百万计的类似问题和解决方案,但相信我--我检查了我能找到的每一个问题,没有一个是有效的。我知道为什么会有这个问题,我也知道如何解决,但是......它就是不工作,我不知道为什么。我在后端使用Spring,在前端使用React。这是一个熟悉的错误。
我想我已经添加了所有应该添加的东西,但不知道为什么这个 CORS 问题仍然存在。在后端,我有WebMvcConfigurer这样的设置。
@Configuration
public class CORSConfig implements WebMvcConfigurer {
private final long MAX_SECS = 3600;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(MAX_SECS);
}
}
正如你所看到的,允许的起源和允许的头文件都被设置了。 当涉及到前端的头文件也被设置了:
const request = (options) => {
const headers = new Headers({
'Content-Type': 'application/json'
})
if(localStorage.getItem(ACCESS_TOKEN)) {
headers.append('Authorization', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
}
const defaults = {headers: headers};
options = Object.assign({}, defaults, options);
return fetch(options.url, options)
.then(response =>
response.json().then(json => {
if(!response.ok) {
return Promise.reject(json);
}
return json;
})
);
};
我已经尝试了所有的方法 ...我不想安装插件,因为它不能解决这个问题。我只想知道为什么它不工作,以及如何才能使它工作。有什么想法吗?