【问题标题】:How to fetch data from mongodb in MERN如何在 MERN 中从 mongodb 获取数据
【发布时间】:2018-11-28 03:59:53
【问题描述】:

我在 MEAN Stack 中从 db 获取信息到前端时遇到问题。 我尝试使用 axios 插件来获取数据,但没有显示。 这是代码:

这是我在 mongodb 中的数据:

如何向这部分显示信息(例如:用户名)?

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

【问题讨论】:

  • 你有没有试过用postman工具检查你的api是否完美返回用户数组,没有任何错误。

标签: mongodb reactjs axios fetch-api mern


【解决方案1】:

谢谢, 实际上我只是使用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 });
 })

【讨论】:

    【解决方案2】:

    您可以像下面这样使用,将标头添加到您的 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>
      }
    } 
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 我已经尝试过 &lt;tbody&gt; {this.state.users.map(user =&gt; &lt;tr&gt; &lt;td&gt;{user.name}&lt;/td&gt; &lt;td&gt;{user.email}&lt;/td&gt; &lt;/tr&gt; )} &lt;/tbody&gt; 但仍然没有显示任何内容
      • 尝试在axios.get()中添加catch方法,看看有没有报错。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      相关资源
      最近更新 更多