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}`);
});
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
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
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.
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?
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.What this operator
?
does is tell js to only callmap
ifjokes
is defined and only read the valuestitle
,id
ifjoke
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.
Set jokes to an empty array if there’s an error. you can try this