我正在尝试编写一个用户个人资料页面以从 URL 中获取用户名,例如http://SITE_URL/users/username,并使用该信息通过比较从数据库集合中获取的详细信息来呈现页面,但似乎我正在制作代码周围某处的一个巨大错误。
我对 MERN 堆栈完全陌生。希望能得到帮助。
应用程序.js
app.get('/users/:username', function (req, res) {
var userurl = req.params.username;
user.findByUsername(userurl,function(result){
//res.send(result);
res.sendFile(__dirname + '/html/users.html');
});
})
app.post('/users/:username', function (req, res) {
var newurl = req.params.username;
user.foundByUsername(newurl,function(result){
res.send(result);
//res.sendFile(__dirname + '/html/users.html');
});
})
用户.js
findByUsername: function(userurl, callback){
MongoClient.connect(url, function(err, db){
db.collection('user').findOne( { username : userurl
},function(err, result){
if(result==null){
callback(false)
}
else{
callback(result);
}
});
});
},
foundByUsername: function(newurl, callback){
MongoClient.connect(url, function(err, db){
db.collection('user').findOne( { username : newurl
},
function(err, result){
assert.equal(err, null);
console.log("Retrived the user entry.");
if(err == null){
callback(result)
}
else{
callback(false)
}
});
});
},
用户.jsx
var Router = window.ReactRouter.Router;
var Route = window.ReactRouter.Route;
var hashHistory = window.ReactRouter.hashHistory;
var browserHistory = window.ReactRouter.browserHistory;
var Link = window.ReactRouter.Link;
class UserProfile extends React.Component {
constructor(props){
super(props);
this.foundByUsername = this.foundByUsername.bind(this);
this.state = {
username: '',
}
}
componentDidMount() {
this.foundByUsername();
}
foundByUsername(){
var username = this.props.params.username;
var self = this;
axios.post('/users/:username', {
username: username
})
.then(function (response) {
if(response){
console.log(response);
self.setState({username:response.data.username});
}
})
.catch(function (error) {
console.log('error is ',error);
});
}
render() {
return (
<div>
Username: { this.state.username }<br />
</div>
)
}
}
ReactDOM.render(
<Router history={hashHistory}>
<Route component={UserProfile} path="/users/:username"></Route>
</Router>,
document.getElementById('app'));