I made a form that returns a post as an object and dispatches it to actions/posts.js but running into an error on my browser's web console stated as
POST http://localhost:5000/posts 404 (Not Found)
form.js
const handleSubmit = async (e) => {
try {
e.preventDefault();
dispatch(createPost(postData));
} catch (error) {
console.log(error);
}
};
i think it has something to do with createPost but cant figure out what as i am new to this.
actions/posts.js
export const createPost = (post) => async (dispatch) => {
try {
const { data } = await api.createPost(post);
dispatch({ type: 'CREATE', payload: data });
} catch (error) {
console.log(error);
}
};
api/index.js
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
reducers/posts.js
export default ( posts = [], action ) => {
switch (action.type) {
case 'FETCH_ALL':
return action.payload;
case 'CREATE':
return [ ...posts, action.payload];
default:
return posts;
}
};
my back-end is
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb srv://my username,password';
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true } )
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`))) .catch((err) => console.log(err))
backend routes
import express from 'express';
import { getPosts, createPosts } from '../controllers/posts.js';
const router = express.Router();
router.get('/', getPosts);
router.get('/create', createPosts);
export default router;
i have been following this tutorial of build and deploy an app using MERN. youtube link : https://www.youtube.com/watch?v=ngc9gnGgUdA&list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu&index=19&t=1528s
i tried searching on google what the problem on google but cant figure out the solution. pls help !
CodePudding user response:
POST http://localhost:5000/posts 404 (Not Found)
does not work, because you are defining the backend routes with "GET".
The express router adheres to HTTP verbs.
// GET method route
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})
// POST method route
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
So
router.get('/', getPosts);
router.get('/create', createPosts);
should probably be:
router.get('/', getPosts);
router.post('/create', createPosts);
Fetching posts in the frontend code should then use the "get" verb, and creating posts should use the "post" verb.