Spring boot и React JS: Uncaught (в обещании) Ошибка: запрос не выполнен с кодом состояния 404 - PullRequest
1 голос
/ 17 мая 2019

Я делаю веб-приложение с руководством по udemy в Spring Boot и React JS.У меня все так же, как в этом уроке, но когда я делаю запрос, я получаю эту ошибку:

Ошибка в конце этого поста.

Реагирует структура проекта 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 голосов
/ 17 мая 2019

Проблема здесь http:localhost:8081/users/${name}/todos. Просто измените URL в вашем запросе на http://localhost:8081/users/${name}/todos

Будь внимательнее:)

...