简体   繁体   中英

How to fetch data from mongodb in MERN

I got a problem while getting information from db to frontend in MEAN Stack. i've try using axios plugin to fetch data, but nothing show. 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.

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

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

axios.get('/api/account/profile/info?id=' +id)
  .then(res => {
     this.setState({ user: res.data.user });
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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