[英]How to fetch data from mongodb in MERN
I got a problem while getting information from db to frontend in MEAN Stack. 从数据库向MEAN Stack中的前端获取信息时遇到问题。 i've try using axios plugin to fetch data, but nothing show. 我尝试使用axios插件来获取数据,但没有任何显示。 this is the code: 这是代码:
and this is my data in mongodb: 这是我在mongodb中的数据:
how can i show the information to this part (ex: for username)? 我如何显示此部分的信息(例如:用户名)?
<div className="user-details">
<tr>
<th>Username: </th>
<th></th>
</tr>
</div>
我不确定您的问题到底是什么,您将用户设置为数组,但是在render方法中将其视为“文本”,请尝试使用map方法遍历每个用户并显示每个用户的信息(如果您这样做)从API获取信息时遇到问题,请尝试将客户端package.json中的代理设置为API端口,并在react ComponentDidMount生命周期中使用操作。
You can use like below, Add header to your axios request, set 'crossDomain': true to overcome cors errorr. 您可以使用如下所示的方式,将头添加到axios请求中,将'crossDomain'设置为:true以克服cors错误。
export default class Profile extends Component{
constructor(props){
super(props);
this.state = {
users: []
}
}
conmponentDidMount(){
axios.get('/api/account/profile',{ headers: { 'crossDomain': true, 'Content-Type': 'application/json' } })
.then(res=> {
this.setState({ users: res.data }).then(profileState => {
console.log(JSON.stringify(this.state.users))
}); //It sets the state asynchronously
})
}
render(){
<div>
<div className="user-details">
{
this.state.users.map(user =>
<tr>
<td>Username: </td>
<td>{user.name}</td>
</tr>
)
}
</div>
</div>
}
}
thanks, actually i just used this.state.user.name
without maping to show from database 谢谢,实际上我只是使用了this.state.user.name
而没有映射从数据库中显示
<strong>Name:</strong>{this.state.user.name}<br/>
and in api i get the user id in url to get current user/active user from session. 在api中,我在url中获取用户ID,以从会话中获取当前用户/活动用户。
axios.get('/api/account/profile/info?id=' +id)
.then(res => {
this.setState({ user: res.data.user });
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.