【发布时间】:2021-09-01 14:41:45
【问题描述】:
我有一个 MongoDB,我可以像这样从 Postman 内部提取数据:http://localhost:8080/employees。这工作得很好,但如果我从我的反应前端发出相同的请求,那么什么都不会发生。
这是我的index.js 文件:
ReactDOM.render(
<App />,
document.getElementById('root')
);
这是我的App.js 文件:
import './App.css';
import ListEmployeeComponent from './components/ListEmployeeComponent';
function App() {
return (
<div className="container">
<ListEmployeeComponent/>
</div>
);
}
export default App;
这是我需要显示来自 MongoDB 的数据的组件:
class ListEmployeeComponent extends Component {
constructor(props){
super(props)
this.state = {
employees: []
}
}
compondentDidMount(){
EmployeeService.getEmployees().then((res)=> {
this.setState({employees: res.data})
});
}
render() {
return (
<Fragment>
{console.log(this.props)}
<h2 className="text-center">Employee List</h2>
<div className="row">
<table className="table table-striped table-bordered">
<thead>
<tr>
<th>Employee First Name</th>
<th>Employee Last Name</th>
<th>Employee Email Id</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.employees.map(
employee =>
<tr key = {employee.id}>
<td>{employee.firstName}</td>
<td>{employee.lastName}</td>
<td>{employee.emailId}</td>
</tr>
)
}
</tbody>
</table>
</div>
</Fragment>
);
}
}
export default ListEmployeeComponent;
据我所知,Javascript 控制台只有一条消息:
[HMR] Waiting for update signal from WDS...
那么有什么关系呢?为什么我没有收到 React 的响应,但我在 Postman 和我的 URL 中却收到了。
最后,这是我使用axios的地方:
import axios from 'axios';
const EMPLOYEES_API_BASE_URL = "http://localhost:8080/employees";
class EmployeeService {
getEmployees(){
console.log("hello");
return axios.get(EMPLOYEES_API_BASE_URL);
}
}
// Not exporting the class, but an object of this class so that we can use the object to call these methods ^
export default new EmployeeService();
这是后端的控制器:
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class EmployeeController {
// Auto-inject EmployeeRepository Class into this class so we can use the object
// without calling 'new EmployeeRepository'
@Autowired
private EmployeeRepository employeeRepo;
// GET all employees
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepo.findAll();
}
}
【问题讨论】:
-
您在网络选项卡中看到请求了吗?服务器上的 CORS 设置是否正确?我们需要更多信息来帮助您解决这个问题。
-
好的,我添加了网络选项卡的屏幕截图。看起来对吗?
-
我的控制器中也有@CrossOrigin。我会将其添加到我的问题中。
-
我在网络面板中看不到请求。您确定正在调用
getEmployees方法吗? -
应该是
componentDidMount而不是compondentDidMount。
标签: reactjs react-redux axios