【发布时间】:2021-06-30 17:53:35
【问题描述】:
由于对 Angular 有很好的理解,因此对 React 来说非常陌生。我在 Angular 上遇到过 CORS 问题,并且总是通过后端配置解决这些问题。不幸的是,到目前为止,React 还不是这样。
另外,请注意,这是纯粹用于教育目的的应用程序,没有实际的敏感日期被提交或存储在数据库中。我主要关心的是让这个东西正常工作而不是完美的安全性,因为我的 React 知识仍然很基础。
问题来自于在 React 中使用 fetch 发布到我的 API。 post 方法在 Postman 中运行良好,但在使用浏览器 (Chrome) 时,我收到以下消息:
POST https://bookkeeperdb.herokuapp.com/api/books/add net::ERR_ABORTED 403
Response {type: "cors", url: "https://bookkeeperdb.herokuapp.com/api/books/add", redirected: false, status: 403, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 403
statusText: ""
type: "cors"
url: "https://bookkeeperdb.herokuapp.com/api/books/add"
__proto__: Response
最初,我收到更多关于在我的配置中更具体的信息错误,而不是对所有内容都使用通配符。我对这个问题的所有研究都让我从一个错误跳到另一个错误,并使我后端的 CORS 配置更加具体。但是,我被这个问题困住了,在网上找不到任何相关的解决方案。
这是我的参考代码: FRONTEND(在 REACT 中提交表单):
handleSubmit(event) {
event.preventDefault();
const formFields = {
title: this.state.bookTitle,
synopsis: this.state.synopsisInput,
pageCount: parseInt(this.state.pageCountInput),
isbn: parseInt(this.state.isbnInput),
genre_name: this.state.genreInput,
author_first_name: 'Cormac',
author_last_name: 'McCarthy',
// author_first_name: this.state.authorInput.slice(0, this.state.authorInput.indexOf(" ")),
// author_last_name: this.state.authorInput.slice(this.state.authorInput.indexOf("")),
publisher_name: this.state.publisherInput
}
const headers = new Headers({
'Content-Type' : 'application/json',
'Authorization': `Bearer ${localStorage.token}`
})
console.log(`The following title was submitted: ${formFields.title}`);
fetch("https://bookkeeperdb.herokuapp.com/api/books/add", {
method: 'POST',
credentials: "include",
headers: headers,
body: JSON.stringify(formFields)
})
.then((response) => console.log(response))
.catch(error => console.log(error))
}
BACKEND(SPRING BOOT 中的 corsconfig):
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.allowedOrigins("http://localhost:3000",
"http://localhost:3000/contribute");
}
};
}
}
提前感谢您的帮助。
【问题讨论】:
标签: reactjs spring-boot fetch http-status-code-403