skip to Main Content

Here is the node js
getting error in promise

import express from "express";

const app = express();

const port = process.env.PORT || 3000;

app.get('/jokes', (req ,res) => {
  const jokes = [
    {
      id: 1,
      title: 'Why don't scientists trust atoms?',
      content: 'Because they make up everything!'
    },
    {
      id: 2,
      title: 'Did you hear about the mathematician who's afraid of negative numbers?',
      content: 'He'll stop at nothing to avoid them!'
    },
    {
      id: 3,
      title: 'Why did the scarecrow win an award?',
      content: 'Because he was outstanding in his field!'
    },
    {
      id: 4,
      title: 'Why don't skeletons fight each other?',
      content: 'They don't have the guts!'
    },
    {
      id: 5,
      title: 'What do you call fake spaghetti?',
      content: 'An impasta!'
    }
  ];

      res.send(jokes);        
    }); 


app.listen(port, () => {
  console.log(`Server at http://localhost:${port}`);
});

Error that i am getting

here is react code
Tried using map function in react file and i am getting uncaught TypeError: jokes.map is not a function

import  { useEffect, useState } from "react"
import React from "react"
import axios from 'axios'
import './App.css'
function App() {
  const [jokes, setJokes] = useState([])

  useEffect(() => {
   axios.get('http://localhost:3000/jokes')
   .then((response) =>{
    setJokes(response.data)
   })
   .catch((error) =>{
    setJokes(error)
   })
  }, [])
  

  return (
    <>
     <h1>Fullstack</h1>
      <p>JOKES : {jokes.length}</p>
      
      {
        jokes.map((joke,index) =>{
            <div key={joke.id} >
              <h3>{joke.title}</h3>
              <h3>{joke.title}</h3>
            </div>
        })
      }
    </>
  )
}
export default App

error in frontend

i have tried sending data using app.send and app.json both but it stil showing Uncaught (in promise) in console

also i wont able to map it in react error says jokes.map is not a function

4

Answers


  1. You’re getting a 403 error from your API (permission error), check the logs to see the error.
    The map function can’t work right now because it isn’t receiving an array but an object with an error message.

    Login or Signup to reply.
  2. For some reason your server is declining your request. As a result jokes is undefined.

    There is nothing in your backend code that should be causing this. Have you tried using a different port for your backend?

    Login or Signup to reply.
  3. You are getting this error because jokes is undefined, there are several reasons why that might be happening. Since you asked for a frontend solution for this question, one way to avoid getting this response irrespective of whether jokes is defined or not is to use the optional chaining operation ?. So do something like this instead to avoid getting this kind of error.

    {
      jokes?.map((joke,index) =>{
        <div key={joke?.id} >
          <h3>{joke?.title}</h3>
          <h3>{joke?.title}</h3>
        </div>
      })
    }
    

    What this operator ? does is tell js to only call map if jokes is defined and only read the values title, id if joke is defined.

    You might need to look into your backend code to confirm if you are getting a valid response for the endpoint you are calling.

    Login or Signup to reply.
  4. Set jokes to an empty array if there’s an error. you can try this

    useEffect(() => {
        axios
          .get("http://localhost:3000/jokes")
          .then((response) => {
            setJokes(response.data);
          })
          .catch((error) => {
            console.error("Error fetching jokes:", error);
            setJokes([]);
          });
      }, []);
    
      return (
        <>
          <h1>Fullstack</h1>
          <p>JOKES : {jokes.length}</p>
    
          {(jokes || []).map((joke, index) => (
            <div key={joke.id}>
              <h3>{joke.title}</h3>
              <p>{joke.content}</p> {/* Use joke.content here */}
            </div>
          ))}
        </>
      );
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search