首页 > 解决方案 > 前端提取不起作用,但后端显示 API

问题描述

我一直在尝试从后端获取用户的数据,以将其设置为我的应用程序前端的状态。我正在使用 MERN 堆栈。我正处于学习阶段。做一个关于学习的直接项目过程

app.get("/api/users",(req , res )=>{

        console.log(req.session.passport.user)

        Users.find({"_id":req.user._id},(err,user)=>{
            if(err) {console.log(err)}
            const userjson = JSON.stringify(user)
            res.end(userjson)
        })
        
    })

这里的用户是数据库模型,在前端部分我已经通过 axios 完成了获取

import React,{useEffect, useState,Component} from 'react'
import SectionBar from '../../../Header/NavigationItems/SectionBar'
import AdminShop from './Shop/Shop'
import { Route, Switch } from 'react-router'
import Products from './Products/products'
import Profile from './Profile/Profile'
import axios from 'axios'


 class AdminLayout extends Component {
    constructor(props){
        super(props)
        this.state={
            user:{},
            contetShow:false
        }
    
    }

    componentDidMount() {
        axios.get("http://localhost:4000/api/users").then((response)=>{
        console.log(response)            
        this.setState({
            ...this.state,
            user:response.data,
            contentShow:true
        })
        })
        .catch((err)=>{

            this.setState({
                ...this.state,
                contentShow:false
            })
           
        })
    }

    

    render() {
    const sectionLink = ["shop","products","profile"]

    let Display = this.state.contentShow?<>
    <SectionBar tag ="admin" links={sectionLink}/>
    <Switch>
        <Route path="/admin/shop" exact component={AdminShop}/>
        <Route path="/admin/products" exact component={Products}/>
        <Route path="/admin/profile" exact component={Profile}/>
    </Switch>
    </>:<p>Nothing to display</p>;

        return (
            <>
                {Display}   
            </>
        )
    }
    
}

export default AdminLayout

我期待着回复

标签: node.jsreactjsexpressmern

解决方案


似乎不需要JSON.stringify在后端调用。前端可以将其作为原始 json 接收。

以下代码段应该有助于解决您的问题。

app.get("/api/users", (req, res )=>{
        console.log(req.session.passport.user)

        Users.find({"_id":req.user._id},(err,user)=>{
            if(err) {console.log(err)}
            res.status(200).json({
              status: 'success',
              data: user,
            });
        })
    })

然后,像下面的代码片段一样在前端调用它。

axios.get("http://localhost:4000/api/users").then((response)=> {         
  this.setState({
    ...this.state,
    user: response.data,
    contentShow: true
  });

推荐阅读