reactjs - Spring boot 和 React JS:未捕获(承诺中)错误:请求失败,状态码 404
问题描述
我使用 Spring Boot 和 React JS 中的 udemy 教程制作 Web 应用程序。我的一切都与本教程中的一样,但是当我提出请求时,我收到了这个错误:
文末有错误。
React JS 项目结构:
TodoDataService.js
import axios from 'axios';
class TodoDataService {
retrieveAllTodos(name) {
return axios.get(`http:localhost:8081/users/${name}/todos`);
}
}
export default new TodoDataService();
ListTodosComponent.js
import React from 'react';
import AuthenticationService from './AuthenticationService';
import TodoDataService from '../../api/todo/TodoDataService';
class ListTodosComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: []
}
}
componentDidMount() {
let username = AuthenticationService.getLoggedInUserName();
TodoDataService.retrieveAllTodos(username)
.then(
response => {
this.setState({ todos: response.data })
}
)
}
render() {
return (
<div>
<h1>List Todos</h1>
<div className="container">
<table className="table">
<thead>
<tr>
<th>id</th>
<th>description</th>
<th>Target Date</th>
<th>Is Completed?</th>
</tr>
</thead>
<tbody>
{
this.state.todos.map (
todo =>
<tr key={todo.id}>
<td>{todo.id}</td>
<td>{todo.description}</td>
<td>{todo.done.toString()}</td>
<td>{todo.targetDate.toString()}</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
);
}
}
export default ListTodosComponent;
欢迎组件.js
import React from 'react';
import { Link } from 'react-router-dom';
import HelloWorldService from '../../api/todo/HelloWorldService';
class WelcomeComponent extends React.Component {
constructor(props) {
super(props);
this.retrieveWelcomeMessage = this.retrieveWelcomeMessage.bind(this);
this.state = {
welcomeMessage: ''
}
this.handleSuccessfulResponse = this.handleSuccessfulResponse.bind(this);
this.handleError = this.handleError.bind(this);
}
render() {
return (
<>
<h1>Welcome!</h1>
<div className="container">
Welcome {this.props.match.params.name}
<br />
You can manage your todos <Link to="/todos">here</Link>
</div>
<div className="container">
Click here to get a customized welcome message.
<button onClick={this.retrieveWelcomeMessage} className="btn btn-success">Get Welcome Message</button>
</div>
<div className="container">
{this.state.welcomeMessage}
</div>
</>
);
}
retrieveWelcomeMessage() {
// HelloWorldService.executeHelloWorldService()
// .then(response => this.handleSuccessfulResponse(response));
// HelloWorldService.executeHelloWorldBeanService()
// .then(response => this.handleSuccessfulResponse(response));
HelloWorldService.executeHelloWorldPathVariableService(this.props.match.params.name)
.then(response => this.handleSuccessfulResponse(response))
.catch(error => this.handleError);
}
handleSuccessfulResponse(response) {
console.log(response);
this.setState({welcomeMessage: response.data.message});
}
handleError(error) {
console.log(error);
this.setState({welcomeMessage: error.response.data.message});
}
}
export default WelcomeComponent;
AuthenticationService.js
class AuthenticationService {
registerSuccessfulLogin(username, password) {
sessionStorage.setItem('authenticatedUser', username);
}
logout() {
sessionStorage.removeItem('authenticatedUser');
}
isUserLoggedIn() {
let user = sessionStorage.getItem('authenticatedUser');
if(user === null) {
return false;
}
return true;
}
getLoggedInUserName() {
let user = sessionStorage.getItem('authenticatedUser');
if(user === null) return ''
return user
}
}
export default new AuthenticationService();
包.json
{
"name": "todo-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.0",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "PORT=4200 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
SPRING BOOT 项目结构:
TodoResource 控制器类
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class TodoResource {
@Autowired
private TodoHardcodedService todoService;
@GetMapping("/users/{username}/todos")
public List<Todo> getAllTodos(@PathVariable String username) {
return todoService.findAll();
}
}
TodoHardcodedService 类
@Service
public class TodoHardcodedService {
private static List<Todo> todos = new ArrayList<>();
private static int idCounter = 0;
static {
todos.add(new Todo(++idCounter, "user", "Learn to Dance", new Date(), false));
todos.add(new Todo(++idCounter, "user", "Learn about Microservices", new Date(), false));
todos.add(new Todo(++idCounter, "user", "Learn about Angular", new Date(), false));
}
public List<Todo> findAll() {
return todos;
}
}
Todo 模型类
public class Todo {
private long id;
private String username;
private String description;
private Date targetDate;
private boolean isDone;
// others: constructor with all fields, getters and setters
}
应用程序属性
server.port=8081
如果您对代码有任何疑问或有任何解决此问题的想法,请写。
错误:
xhr.js:173
GET http://localhost:4200/localhost:8081/users/user/todos 404 (Not
Found)
dispatchXhrRequest @ xhr.js:173
xhrAdapter @ xhr.js:18
dispatchRequest @ dispatchRequest.js:49
Promise.then (async)
request @ Axios.js:55
Axios.<computed> @ Axios.js:65
wrap @ bind.js:11
retrieveAllTodos @ TodoDataService.js:5
componentDidMount @ ListTodosComponent.js:15
commitLifeCycles @ react-dom.development.js:18109
commitAllLifeCycles @ react-dom.development.js:19668
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:19892
(anonymous) @ react-dom.development.js:21440
unstable_runWithPriority @ scheduler.development.js:255
completeRoot @ react-dom.development.js:21439
performWorkOnRoot @ react-dom.development.js:21362
performWork @ react-dom.development.js:21267
performSyncWork @ react-dom.development.js:21241
requestWork @ react-dom.development.js:21096
scheduleWork @ react-dom.development.js:20909
scheduleRootUpdate @ react-dom.development.js:21604
updateContainerAtExpirationTime @ react-dom.development.js:21630
updateContainer @ react-dom.development.js:21698
push../node_modules/react-dom/cjs/react-
dom.development.js.ReactRoot.render @ react-
dom.development.js:22011
(anonymous) @ react-dom.development.js:22163
unbatchedUpdates @ react-dom.development.js:21486
legacyRenderSubtreeIntoContainer @ react-dom.development.js:22159
render @ react-dom.development.js:22234
./src/index.js @ index.js:7
__webpack_require__ @ bootstrap:781
fn @ bootstrap:149
0 @ serviceWorker.js:135
__webpack_require__ @ bootstrap:781
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
Show 8 more frames
createError.js:17
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
解决方案
问题就在这里http:localhost:8081/users/${name}/todos
。只需在您的请求中更改为 url 即可http://localhost:8081/users/${name}/todos
更加专心:)
推荐阅读
- python - Kivy Accordion:空间不足警告
- javascript - Google reCaptcha v3 将成功返回为 false
- javascript - 即使使用 setTimeout 也无法在同一块中重新打开子窗口
- python - 如何使用 pandas_profiling 对表进行数据分析
- java - 在多个包中创建可访问的编写器
- c# - 调用某个 url 时尝试重定向
- c# - 垃圾收集器在执行低级 C++ 代码时过早(可能)启动
- angular - 我的 Angular7 应用程序中的 HttpInterceptor 在错误期间没有触发,我的代码有什么问题?
- bash - 找出调用(shell)脚本的内容
- javascript - 应用从后台移到前台时触发哪个 JS 事件