繁体   English   中英

如何在MERN中从mongodb获取数据

[英]How to fetch data from mongodb in MERN

从数据库向MEAN Stack中的前端获取信息时遇到问题。 我尝试使用axios插件来获取数据,但没有任何显示。 这是代码: 个人资料页

这是我在mongodb中的数据: mongodb

我如何显示此部分的信息(例如:用户名)?

<div className="user-details">
   <tr>
     <th>Username: </th>
     <th></th>
   </tr>
</div>

我不确定您的问题到底是什么,您将用户设置为数组,但是在render方法中将其视为“文本”,请尝试使用map方法遍历每个用户并显示每个用户的信息(如果您这样做)从API获取信息时遇到问题,请尝试将客户端package.json中的代理设置为API端口,并在react ComponentDidMount生命周期中使用操作。

您可以使用如下所示的方式,将头添加到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>
  }
} 

谢谢,实际上我只是使用了this.state.user.name而没有映射从数据库中显示

<strong>Name:</strong>{this.state.user.name}<br/>

在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM