我从Web开发开始。 我使用create-react-app来创建我的项目。 我现在能够渲染不同的页面并在页面之间建立完美的路径。
现在,我正在尝试添加项目的后端部分。 我正在使用express,可能会使用MongoDB,但我无法弄清楚如何管理从客户端到服务器的调用。 这是我的例子: 1.在App.js中我有以下内容,只是一个简单的登录页面:
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import logo from './logo.svg';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import './App.css';
import api from './api'
import { browserHistory } from 'react-router'
class App extends Component {
goToUsers () {
api.login()
}
render() {
return (
<MuiThemeProvider>
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<br />
<br />
<TextField hintText="Login" />
<br />
<TextField hintText="Password" type="password" />
<br />
<br />
<RaisedButton label="Login" onTouchTap={this.goToUsers}/>
</div>
</MuiThemeProvider>
);
}
}
export default App;
登录函数显然应该从客户端获取数据但是现在我只在api.js中有一个简单的函数,我想集中我的api函数:
class Api {
login () {
fetch('localhost:3000/users')
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
}
}
export default new Api()
最后是index.js
import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Router, Route, IndexRoute, IndexRedirect, browserHistory, Link } from 'react-router'
import App from './App';
import Users from './users';
injectTapEventPlugin();
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App} />
<Route path="/Users" component={Users} />
</Router>
, document.getElementById('root'))
为了简单起见,我没有复制users.js和其他对象,但是当转到http://localhost:3000/或http://localhost:3000/users时,所有类都可以正常工作
然而,当我点击按钮时,我收到错误Unhandled Rejection(TypeError):无法获取。
知道我缺少什么吗?
答案 0 :(得分:0)
class App extends Component {
constructor(props) {
super(props);
state = { users: null }
}
goToUsers() {
//just put your request directly in the method
fetch('http://localhost:300/users')
.then(response => {
//do something with response
const users = response.json();
this.setState({ users })
})
.catch(err => {
throw new Error(err)
})
}
render() {
return (
<MuiThemeProvider>
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<br />
<br />
<TextField hintText="Login" />
<br />
<TextField hintText="Password" type="password" />
<br />
<br />
<RaisedButton label="Login" onTouchTap={this.goToUsers}/>
</div>
</MuiThemeProvider>
);
}
}