簡體   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