【发布时间】:2020-02-04 19:53:36
【问题描述】:
我正在编写一个程序,它在后端使用 spring-boot(使用 maven)和 PostgreSQL 数据库,并在前端响应 js。
最初,我有一个表示单个网页的 test.js 文件,该文件创建了一个获取请求来与后端控制器通信,而后端控制器反过来又更新了数据库。这很有效,所以我想更进一步,使用 react-router 在前端链接多个页面。但是,当我尝试实现 react-router 时,它导致我的初始获取请求返回 404(未找到)。
这是我的新 test.js 文件中的一个获取请求的示例。
const line = {
name: this.state.name,
id: this.state.id
};
const fetchOptions = {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body : JSON.stringify(line)
};
let url = "/create";
console.log("creating");
fetch(url, fetchOptions)
.then(response => response.json())
.then(message => {
this.setState({message: message.text})
})
.catch((error) => {
console.log("error: ", error.message);
})
这是我实现 react-router 的 main.js 代码:
import React, { Component } from "react";
import {
Route,
NavLink,
Switch,
HashRouter
} from "react-router-dom";
import Home from "./Home";
import Test from "./Test";
class Main extends Component {
render() {
return (
<HashRouter>
<div>
<h1>Simple SPA</h1>
<ul className="header">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/Test">Test</NavLink></li>
</ul>
<Switch className="content">
<Route exact path="/" component={Home}/>
<Route path="/Test" component={Test}/>
</Switch>
</div>
</HashRouter>
);
}
}
export default Main;
最后,看看控制器是如何接收请求的:
@PostMapping("/create")
@ResponseBody
public ResponseTransfer createTransfer(@RequestBody String student) {
// Code to update database
...
return new ResponseTransfer(student);
}
重申一下:这里的基本思想是通过 react-router 链接有一个主页和一个测试页面。测试页面有一个文本字段和一个按钮,允许用户在数据库中“创建”一个条目。问题在于,当用户单击“创建”时,会向 Test.js 文件中的“/create”发出提取请求。但是,它没有到达后端控制器中的 @PostMapping("/create"),而只是得到一个 404(未找到)。任何帮助,将不胜感激。谢谢!
【问题讨论】:
-
如果你得到一个 404 意味着你正在访问后端服务器,并且 spring 应用程序正在回复 404 Not Found,所以我建议你使用 chrome 中的调试器来查看你的确切地址前端正在调用,然后查看它是否匹配正确的地址。
-
是服务于 react 应用程序的 spring 应用程序,还是它们彼此独立运行。 react app是localhost:3000,spring app是localhost:8080?
-
是的,我确认两个地址都是“localhost:3000/create”。 spring 应用程序 (localhost:8080) 和 react 应用程序 (localhost:3000) 彼此独立运行。谢谢!
标签: reactjs spring-boot react-router http-status-code-404