'Frontend fetch not working but backend shows the API

I have been trying to fetch the user's data from the backend to set it to the state in the front-end of my application. I am using MERN stack. I am on my learning phase. Doing a direct project process on learning

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)
        })
        
    })

Here Users is the database model and In the front end part I have done fetching through 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

I am looking forward for the response



Solution 1:[1]

There seems to be a typo in your constructor.. this.state has contetshow=false, but you use contentshow in your application. Now that should not matter since the error you describe is a type error, saying that you are missing values. What is the result of the console.log(response)? This probably does not contain data, which is why your user is undefined

Solution 2:[2]

There does not seem to be any need to call JSON.stringify at the backend. The front-end can receive it just fine as raw json.

The following snippet should help to fix your problem.

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,
            });
        })
    })

Then, call it in the front-end like the following snippet.

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

Solution 3:[3]

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

  async componentDidMount() {
    try{
      let rs = await axios.get("http://localhost:4000/api/users")
      if (rs){
        this.setState({user : rs.data})
        this.setState({contentShow : true})
      }
    }
    catch(e){
      return this.setState({contentShow : false})
    }
  }


  render() {
    return (
      <>
        {this.state.contentShow ? (
         // your Code
          console.log("user", this.state.user)
        ) : (
          <p>Nothing to display</p>
        )}
      </>
    );
  }
}

export default App;

If you getting user undefined in console then please check network tab in developer tools may be there is problem with your backend

Solution 4:[4]

App.js:

import KonyvtarApp from './KonyvtarApp';
function App() {return (<KonyvtarApp />);}
export default App;

KonyvCard.jsx:

import React, { Component } from 'react';
class KonyvCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      errors: "",
      rented: false
    };
  }

  handleRent = (book_id) => {
    fetch(`http://localhost:8000/api/books/${book_id}/rent`, {
      method: "POST",
    }).then(async response => {
      if (response.status === 200) {
        this.setState({
          errors: "",
          rented: true
        })
      } else {
        const data = await response.json();
        this.setState({
          errors: data.message,
          rented: false
        })
      }
    });
  }

  render() {
    const { book } = this.props;
    const { rented, errors } = this.state;
    return (
      <div className="col-sm-12 col-md-6 col-lg-4 card">
        <div className="card-body">
          <h2>{book.title}</h2>
          <h2>{book.author}</h2>
          <p>Kiadási év: {book.publish_year}</p>
          <p>Hossz: {book.page_count} oldal</p>
          <img className='img-fluid' src={'szerzok/' + book.author + '.jp                   g'} alt={book.author} />
            <button className='btn btn-light mt-3' onClick={() => this.handleRent(book.id)}>Kölcsönzés</button>
          <p>
              {rented ? "Sikeres foglalás" : errors !== "" ? errors : ""}
          </p>
       </div>
     </div>
  );
 }
}

export default KonyvCard;

Solution 5:[5]

KonyvCard.jsx:

//imrc
import React, { Component } from 'react';
///cc
class KonyvCard extends Component {
constructor(props) {
    super(props);
    this.state = {errors: "",rented: false};}
handleRent = (book_id) => {
fetch(`http://localhost:8000/api/books/${book_id}/rent`, {method: "POST",}).then(async response => {
if (response.status === 200) {this.setState({errors: "",rented: true})
} else {
            const data = await response.json();
            this.setState({
                errors: data.message,
                rented: false})}});}
render() {
    const { book } = this.props;
    const { rented, errors } = this.state;
    return (<div className="col-sm-12 col-md-6 col-lg-4 card">
    <div className="card-body">
    <h2>{book.title}</h2>
                <h2>{book.author}</h2>
                <p>Kiadási év: {book.publish_year}</p>
                <p>Hossz: {book.page_count} oldal</p>
                <img className='img-fluid' src={'szerzok/' + book.author + '.jpg'} alt={book.author} />
                <button className='btn btn-light mt-3' onClick={() => this.handleRent(book.id)}>Kölcsönzés</button>
                <p>
                    {rented ? "Sikeres foglalás" : errors !== "" ? errors : ""}
                </p>
            </div>
        </div>);}}
//export
export default KonyvCard;

Solution 6:[6]

    import React, { Component } from 'react';
    import KonyvList from './KonyvList';
    import KonyvForm from './KonyvForm';
    import KonyvtarFooter from './KonyvtarFooter';
    import KonyvtarHeader from './KonyvtarHeader';

    class KonyvtarApp extends Component {
    constructor(props) {
        super(props);
        this.state = {
            books: [],
            title: "",
            author: "",
            publish_year: "",
            page_count: "",
            errors: "",
        };
    }
    componentDidMount() {
        this.getKonyvek();
    }

    render() {
        const form_id = "konyv_form";
        const { books, title, author, publish_year, page_count, errors } = this.state;
        const form_state = {
            title: title,
            author: author,
            publish_year: publish_year,
            page_count: page_count,
            errors: errors
        };
        return (
            <div className="container mb-3">
                <KonyvtarHeader form_id={form_id} />
                <main className='mt-3 mb-3'>
                    <KonyvList books={books} rentClick={this.handleRent} />
                    <KonyvForm form_id={form_id} formState={form_state}
                        onTitleInput={this.handleTitleInput}
                        onAuthorInput={this.handleAuthorInput}
                        onPublishYearInput={this.handlePublishYearInput}
                        onPageCountInput={this.handlePageCountInput}
                        onClick={this.handleFelvetel}
                    />
                </main>
                <KonyvtarFooter keszito="" />
            </div>
        );
    }

    handleTitleInput = (value) => {
        this.setState({
            title: value
        });
    }
    handleAuthorInput = (value) => {
        this.setState({
            author: value
        });
    }
    handlePublishYearInput = (value) => {
        this.setState({
            publish_year: value
        });
    }
    handlePageCountInput = (value) => {
        this.setState({
            page_count: value
        });
    }
    handleFelvetel = () => {
        const { title, author, publish_year, page_count } = this.state;
        const book = {
            title: title,
            author: author,
            publish_year: publish_year,
            page_count: page_count,
        };
        
        fetch("http://localhost:8000/api/books", {
            method: "POST", 
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(book)
        }).then(async response => {
            if (response.status === 201) {
                this.setState({
                    title: "",
                    author: "",
                    publish_year: "",
                    page_count: "",
                    errors: "",
                })
                this.getKonyvek();
            } else {
                const data = await response.json();
                this.setState({
                    errors: data.message
                })
            }
        });
    }


    async getKonyvek() {
        fetch("http://localhost:8000/api/books")
        .then(async response => {
            if (response.status === 200) {
                const data = await response.json();
                this.setState({
                    books: data.data
                })
            }
        });
    }
}

export default KonyvtarApp;

Solution 7:[7]

App.css

.App { text-align: center;}

.App-logo {

height: 40vmin; pointer-events: none;}

@media (prefers-reduced-motion: no-preference) {
.App-logo {animation: App-logo-spin infinite 20s linear;}}
.App-header {background-color: #282c34;min-height: 100vh;display: flex;
flex-direction: column;align-items: center;justify-content: center;
font-size: calc(10px + 2vmin);color: white;}
.App-link {color: #61dafb;}

Solution 8:[8]

App.js

import './App.css';
import PeopleList from './PeopleList'; //importálni kell!!!
//import bootstrap annak npm install bootstrap után

import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/js/bootstrap.bundle.min';

function App() {return (
<div className="container">
  <PeopleList />
</div>);}
export default App;

// új komponens létrehozásával kezdjük: PeopleList.jsx

Solution 9:[9]

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';


ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,
document.getElementById('root'));

PeopleCard:

//imrc
import React, { Component } from 'react';
///cc
class PeopleCard extends Component {
render() {const { people, torlesClick } = this.props;
return ( <div className="col-sm-6 cold-md-4 col-lg-3
     PeopleCard">
    <div className="card h-100 PeopleCard-card">
      <div className="card-header text-truncate PeopleCard-card-header"><span className="font-weight-bold">Name: </span>
        {people.name}
      </div>
      <div className="card-body PeopleCard-card-body">
        <ul className="list-group list-group-flush">
          <li className="list-group-item"><span className="font-weight-bold">Email: </span>{people.email}</li>
          <li className="list-group-item"><span className="font-weight-bold">Age: </span>{people.age}</li>
        </ul>
      </div>
      <div className="card-footer">
        <button onClick={() => torlesClick(people.id)} className="btn btn-danger">Törlés</button>
      </div>
    </div>
  </div> );
}

}

export default PeopleCard;

Solution 10:[10]

PeopleList.jsx új komponens létrehozásával kezdjük jsx file formátumban (el?nye emet b?vítmény m?ködni fog és alt+shit+f -el tudok formázni) ehhez importálnom kell a react-et, imr vagy imrc parancs kiadásával import React, { Component } from 'react'; import PeopleCard from './PeopleCard'; cc - vel egy class componentet tudok létrehozni vagy ccc konstruktorral PeopleL

class PeopleList extends Component {
constructor(props) {
    super(props);
    this.state = {
        people: []}}
componentDidMount() {
    this.getPeople();}
getPeople(){
    fetch("http://localhost:8000/api/people")
    .then(response => response.json())
    .then(data => this.setState({
        people: data
    }));}
handleTorlesClick = (id) => {
    fetch(`http://localhost:8000/api/film/${id}`, {method: "DELETE"})
    .then(response => console.log(response))}
render(){ 
    // CardList listába veszem fel
    const {people} = this.state;
    const cardList = [];
people.forEach(people => {
        cardList.push(<PeopleCard torlesClick={this.handleTorlesClick} key={people.id} people={people} />);
    });;
return ( <div className="row gy-3">
        {cardList}
        <PeopleCard people={people}/>


    </div> );}

}

export default PeopleList ; //card megjelenítése npm start-al leellen?rzöm, --> localhost:3000; App.js-ben //megjelenítése szükséges (teszt) vagy CardList

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daan Hendriks
Solution 2 Nicholas
Solution 3 Akhil
Solution 4 Evren
Solution 5 Paul Black
Solution 6 bguiz
Solution 7 Paul Black
Solution 8 Paul Black
Solution 9 Paul Black
Solution 10 Paul Black