尝试将我的公司数据发布到 MongoDB Atlas 服务器时出现 Axios POST 错误

问题描述 投票:0回答:1

我正在开发一个 MERN 堆栈项目,我必须将表单数据发布到我的 MongoDB Atlas 数据库。在我的 UserForm.js 文件中,我使用 axios 将表单值发送到服务器以将其保存到数据库。 但我在浏览器检查中收到 Axios 错误和 404 无法找到资源错误。

这是代码:

UserForm.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.
api post axios http-status-code-404 mern
1个回答
0
投票

检查 cors 上和你的环境中请求的端口

这里的端口是3000

app.use(cors({
  origin: "http://localhost:3000"
}));

您可以通过 5000 端口发送请求:

  const response = await axios.post('http://localhost:5000/users', userData);
© www.soinside.com 2019 - 2024. All rights reserved.