我正在遵循一个学习ReactJS的教程,我正在尝试使用Maven创建Spring Boot和React Java Full Stack Application。
以下是我创建的文件:
App.js
import React, { Component } from "react";
import "./App.css";
import InstructorApp from "./component/InstructorApp";
class App extends Component {
render() {
return (
<div className="container">
<InstructorApp />
</div>
);
}
}
export default App;
ListCoursesComponent.jsx:
import React, { Component } from "react";
import CourseDataService from "../service/CourseDataService";
class ListCoursesComponent extends Component {
constructor(props) {
super(props);
this.refreshCourses = this.refreshCourses.bind(this);
}
componentDidMount() {
this.refreshCourses();
}
refreshCourses() {
CourseDataService.retrieveAllCourses(INSTRUCTOR) //HARDCODED
.then(response => {
console.log(response);
});
}
}
export default ListCoursesComponent;
InstructorApp.jsx:
import React, { Component } from "react";
import ListCoursesComponent from "../component/ListCoursesComponent";
class InstructorApp extends Component {
render() {
return (
<>
<h1>Instructor Application</h1>
<ListCoursesComponent />
</>
);
}
}
export default InstructorApp;
CourseDataService.js:
import axios from "axios";
const INSTRUCTOR = "in28minutes";
const COURSE_API_URL = "http://localhost:8080";
const INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}`;
class CourseDataService {
retrieveAllCourses(name) {
return axios.get(`${INSTRUCTOR_API_URL}/courses`);
}
}
export default new CourseDataService();
当我在我的应用程序中吃午餐时,在本教程中,我应该得到以下错误:
[错误] Access-Control-Allow-Origin不允许起源http://localhost:3000。
[错误]由于访问控制检查,XMLHttpRequest无法加载http://localhost:8080/instructors/in28minutes/courses。
[错误]无法加载资源:Access-Control-Allow-Origin不允许使用来源http://localhost:3000。 (课程,第0行)
[错误]未处理的承诺拒绝:错误:网络错误
(匿名函数)(0.chunk.js:1097)
promiseReactionJob
但是当我午餐我的应用程序时,出现此错误:
./src/component/ListCoursesComponent.jsx
Line 15:42: 'INSTRUCTOR' is not defined no-undef
Search for the keywords to learn more about each error.
答案 0 :(得分:3)
未处理的承诺拒绝意味着在某个时候发出了调用您的URL的请求,但该请求被拒绝了,这可能是因为您需要将CORS激活到您的项目中。您可以了解有关CORS的更多信息,并将其添加到项目here。
答案 1 :(得分:2)
您在INSTRUCTOR
中声明了ListCoursesComponent.jsx
,但是您试图在其他文件中使用它。如果要执行此操作,则需要将其导出到定义位置,然后将其导入使用的文件中。
答案 2 :(得分:0)
解决方案:
如@emoore所述,我已通过以下方式在springboot支持的应用程序中添加了CORS:
@CrossOrigin(origins = { "http://localhost:3000", "http://localhost:4200" })
@RestController
如@trixn所述,我通过以下方式将INSTRUCTOR Const导入到ListCoursesComponent文件中:
import INSTRUCTOR from "../service/CourseDataService";