Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Spring引导和反应JS:Uncaught(承诺中)错误:请求失败,状态代码404_Reactjs_Spring Boot_Http Status Code 404 - Fatal编程技术网

Reactjs Spring引导和反应JS:Uncaught(承诺中)错误:请求失败,状态代码404

Reactjs Spring引导和反应JS:Uncaught(承诺中)错误:请求失败,状态代码404,reactjs,spring-boot,http-status-code-404,Reactjs,Spring Boot,Http Status Code 404,我使用Spring Boot和React JS中的教程制作web应用程序。我拥有与本教程中相同的一切,但当我提出请求时,会出现以下错误: 这篇文章结尾的错误 项目结构: TodoDataService.js import axios from 'axios'; class TodoDataService { retrieveAllTodos(name) { return axios.get(`http:localhost:8081/users/${name}/todos`); } }

我使用Spring Boot和React JS中的教程制作web应用程序。我拥有与本教程中相同的一切,但当我提出请求时,会出现以下错误:

这篇文章结尾的错误

项目结构:

TodoDataService.js

import axios from 'axios';

class TodoDataService {
retrieveAllTodos(name) {
    return axios.get(`http:localhost:8081/users/${name}/todos`);
}
}
export default new TodoDataService();
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();
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;
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;
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项目结构:

ToDorSource控制器类

@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();
}
}
应用程序属性

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)
xhr.js:173
得到http://localhost:4200/localhost:8081/users/user/todos 404(不是
发现)
dispatchxhrequest@xhr.js:173
xhrAdapter@xhr.js:18
dispatchRequest@dispatchRequest.js:49
Promise.then(异步)
request@Axios.js:55
Axios@Axios.js:65
wrap@bind.js:11
retrieveAllTodos@TodoDataService.js:5
componentDidMount@listtomoscomponent.js:15
committelifecycles@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
commitrot@react dom.development.js:19892
(匿名)@react dom.development.js:21440
不稳定的\u runWithPriority@scheduler.development.js:255
completeRoot@react dom.development.js:21439
performworkroot@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
updateContainerExpirationTime@react dom.development.js:21630
updateContainer@react dom.development.js:21698
推送../node_模块/react dom/cjs/react-
dom.development.js.ReactRoot.render@react-
dom.development.js:22011
(匿名)@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
(匿名)@main.chunk.js:1
再显示8帧
createError.js:17
未捕获(承诺中)错误:请求失败,状态代码404
在createError(createError.js:17)
结算时(结算js:19)
在XMLHttpRequest.handleLoad(xhr.js:78)

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


注意点:)

谢谢,非常感谢,请不要注意:(@scipio如果解决方案有效,请检查我的答案是否正确:)
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)