Error fetching data:
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_REQUEST"
I am trying to connect my server.js and App.jsx using api (axios module) and expecting the data to get saved in my mongodb document. But It's not happening instead I am getting an error.
here is my server.js code `
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 3001;
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect('mongodb://localhost:27017/yourDB', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
const postSchema = mongoose.Schema({
title: String,
content: String
});
const Post = mongoose.model('Post', postSchema);
// API endpoint for fetching data
app.get("/api/posts", (req, res) => {
Post.find({}, (err, posts) => {
if (err) {
console.error('Error fetching posts:', err);
res.status(500).json({ error: 'Internal server error' });
} else {
res.json(posts);
}
});
});
// API endpoint for creating new data
app.post("/api/posts", (req, res) => {
const { title, content } = req.body;
const newPost = new Post({ title, content });
newPost.save((err, savedPost) => {
if (err) {
console.error('Error saving post:', err);
res.status(500).json({ error: 'Internal server error' });
} else {
res.json(savedPost);
}
});
});
// API endpoint for deleting data
app.delete("/api/posts/:id", (req, res) => {
const { id } = req.params;
Post.findByIdAndDelete(id, (err) => {
if (err) {
console.error('Error deleting post:', err);
res.status(500).json({ error: 'Internal server error' });
} else {
res.json({ message: 'Post deleted successfully' });
}
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
` here is my app.jsx code
import React, { useEffect, useState } from "react";
import axios from "axios";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";
function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
axios.get("/api/posts")
.then(response => {
setNotes(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
function addNote(note) {
setNotes(prevNotes => {
return [...prevNotes, note];
});
axios.post("/api/posts", note)
.then(response => {
console.log("Post saved successfully:", response.data);
})
.catch(error => {
console.error("Error saving post:", error);
});
}
function deleteNote(id) {
setNotes(prevNotes => {
return prevNotes.filter((noteItem, index) => {
return index !== id;
});
});
axios.delete(`/api/posts/${id}`)
}
return (
<div>
<Header />
<CreateArea onAdd={addNote} />
{notes.map((noteItem, index) => (
<Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/>
))}
<Footer />
</div>
);
}
export default App;
Axios needs not only the path
but also the whole url
.
Instead of only using /api/posts
, please try to use something like: http://localhost:3001/api/posts
which depends on your server domain and port.
Sometimes it is exhausted to add whole url every time when calling api. Axios Instance would be a nice choice to simplify these steps.