我如何解决reactjs上的错误POST http:// localhost:3000 / users.json 404(未找到?)?

问题描述 投票:0回答:1
基本上,我有一个名为users.json的json文件。 (在公用文件夹上)

[{ "username": "Antonio", "bestscore": "100" }, { "username": "Tomé", "bestscore": "200" } ]

而且我想用两个变量在该json文件上添加新用户:用户名和最佳分数

我正在做一个记忆游戏,当用户输入初始页面时,写上他的用户名。用户输入用户名后,我想将其用户名添加到json文件中,将其作为默认的bestscore:0。这是我的初始页代码:

class App extends React.Component { constructor(props) { super(props); this.state = { page: "game", showInicio: false, userInput:"", userInfo:[] }; this.changePage = this.changePage.bind(this); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } changePage(page) { this.getUserInfo() this.setState({ page }); } handleChange(event) { this.setState({userInput: event.target.value}); } handleSubmit(event) { alert('Username was submitted: ' + this.state.userInput); event.preventDefault(); this.setState({ showInicio: !this.state.showInicio }); this.postUserInfo() } postUserInfo(){ fetch("users.json", { method: "post", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, //make sure to serialize your JSON body body: JSON.stringify({ username: this.state.userInput, bestscore: 0 }) }) .then( (res) => { console.log(res) }); } render() { if (this.state.showInicio === false){ return ( <div> <div className="inicio"> <h1> Memory game </h1> </div> <div className="iniciodentro"> <form onSubmit={this.handleSubmit}> <label> Enter your username: <input type="text" value={this.state.userInput} onChange={this.handleChange}/> </label> <input type="submit" value="Submit" /> </form> </div> </div> ); }else{ const { page } = this.state; return ( <div className="App"> <NavBar page={page} changePage={this.changePage} /> <div className="App-header"> {page === "game" && <Game username = {this.state.userInput}/>} {page === "leaderboard" && <LeaderBoard />} </div> </div> ); } } } export default App;

我收到此错误:POSThttp://localhost:3000/users.json404(未找到)

任何人都可以帮助我吗?

基本上,我有一个名为users.json的json文件。 (它在公用文件夹上)[{“ username”:“ Antonio”,“ bestscore”:“ 100”},{“ username”:“Tomé”,“ bestscore”:“ 200”}]我想添加。 ..

reactjs
1个回答
0
投票
之所以找不到它,是因为没有在任何地方提供users.json。它只是一个文件。为了使用fetch,它需要命中某种类型的终结点(终结点是托管在服务器上的位置,即examplesite.com/aboutme->关于我的位置是托管在网站examplesite.com上的终结点)。
© www.soinside.com 2019 - 2024. All rights reserved.