I am working on a MERN stack project where I have to post the form data to my MongoDB Atlas Database. In my UserForm.js file I use axios to send the form values to the server to save it to the database.
But I get an Axios Error and a 404 Unable to find resource error in my browser inspect.
Here is the code:
UserForm.js(A react program that takes the form data and sends it to the server using Axios):
// client/src/components/UserForm.js
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const UserForm = () => {
const [userData, setUserData] = useState({
name: '',
location: '',
email:''
});
const history = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
console.log("Entered server to save data of user.")
console.log('Sending request to:', '/api/users'); // Add this line
console.log('Form data to be sent:', userData); // Add this line
const response = await axios.post('http://localhost:5000/users', userData);
console.log('Form submitted successfully:', response.data);
}
catch (error) {
console.error('Error submitting form:', error);
}
};
return (
<div>
<h2>User Form</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={userData.name}
onChange={(e) => setUserData({ ...userData, name: e.target.value })}
/>
<br />
<label htmlFor="location">Location:</label>
<input
type="text"
id="location"
value={userData.location}
onChange={(e) => setUserData({ ...userData, location: e.target.value })}
/>
<br />
<label htmlFor="Email">Email:</label>
<input
type="email"
id="email"
value={userData.email}
onChange={(e) => setUserData({ ...userData, email: e.target.value })}
/>
<br />
<br /> <button type="submit">Submit</button>
</form>
</div>
);`
};
export default UserForm;`
```
Here is the model/User.js file( Defines the schema for the database):
```
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true, required: false },
location: {type: String, required: true}
});
const User = mongoose.model('User', userSchema);
```
module.exports = User;
```
This is my Routes.js file:
```
const express = require('express');
const router = express.Router();
const User = require('../models/User');
router.post('/users', async (req, res) => {
try {
const userData = req.body;
console.log('Received user data:', userData);
const user = new User(userData);
const savedUser = await user.save();
res.json(savedUser);
console.log(savedUser)
} catch (error) {
console.error('Error processing /users route:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
module.exports = router;
```
This is my server.js file:
```
// server/server.js
const express = require('express');
const cors = require('cors');
const serviceProviderRoutes = require('./routes/ServiceProviderRoutes');
const userRoutes = require('./routes/UserRoutes');
const connectDB = require('./db');
const seedDatabase = require('./seedDB');
const User = require('./models/User');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors({
origin: "http://localhost:3000"
}));
app.use(express.json());
connectDB()
.then(() => seedDatabase())
.then(() => {
console.log("from server");
//trying this
app.use('/api/users', userRoutes);
app.use('/api/serviceproviders', serviceProviderRoutes);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
})
.catch((error) => {
console.error('Error during server setup:', error);
});
```
I have made sure that the route paths are named correctly and there are no typos.
I checked in the inspect(Network) of my browser also.
Tried in multiple browsers.
Restarted the server multiple times to see if anything changes.
Nothing helped.
2
Answers
Check the requested port on cors and in ur env
the port here is 3000
U send the request here at 5000 port and the pathname is not api/users:
——>
You should be calling
const response = await axios.post('http://localhost:5000/api/users', userData);
/api
is missing in the request