Spring boot和React JS:未捕获(承诺)错误:请求失败,状态码为404

时间:2019-05-17 13:40:31

标签: reactjs spring-boot http-status-code-404

我使用Spring Boot和React JS中的udemy教程制作Web应用程序。我拥有与本教程相同的所有内容,但是当我发出请求时出现此错误:

此帖子结尾处的错误。

反应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;

WelcomeComponent.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();

package.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
}

application.properties

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)

1 个答案:

答案 0 :(得分:0)

问题在这里http:localhost:8081/users/${name}/todos。 只需将您请求中的url更改为http://localhost:8081/users/${name}/todos

更专心:)