我正在做一个MERN堆栈项目,我必须将表单数据发布到我的MongoDB Atlas数据库。在我的UserForm.js文件中,我使用axios将表单值发送到服务器以保存到数据库。但是我在浏览器检查中收到Axios错误和404无法找到资源错误。
代码如下:
js(一个react程序,它获取表单数据并使用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.
字符串
1条答案
按热度按时间q35jwt9p1#
您应该调用
const response = await axios.post('http://localhost:5000/api/users', userData);
请求中缺少/api