FetchingDataFromAPI Using ReactJS and NodeJS
FetchingDataFromAPI Using ReactJS and NodeJS
js API
npm init
This command creates a `package.json` file that will manage our project's dependencies.
];
res.send(data);
});
app.listen(3000, () => {
console.log(`Server Started`);
});
useEffect(() => {
setData(responseData);
fetchPosts();
}, [])
return (
<section>
{data.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</section>
);
}
What this code does:
- In the `fetchPosts` function, we make a GET request to our API and update the state
with the response.
app.use(cors());
Place these lines after the `const app = express();` line and before defining any
routes.
2. Start your React application (assuming you're using Create React App):
npm start
Now, your React application should be able to fetch and display data from your Node.js
API!
Conclusion
This guide demonstrates how to create a simple API with Node.js and Express, and how
to fetch and display that data in a React application. Remember to handle errors and add
more complex functionality as needed in a real-world application.