Home > Back-end >  Axios post request not working React Nodejs Mongodb
Axios post request not working React Nodejs Mongodb

Time:10-22

I am trying to post a data to the mongoose database but I keep getting Axios error 404. I need help. Is there something wrong in my code?

This is my modal, it contains the front end of the website

AddForm.jsx

import React, { useState } from "react";
import axios, { Axios } from "axios";

const AddForm = () =>{

    const [appData, setAppData] = useState({
        pName:"",
        appNum:"",
        datetime:"",
    })

const submit =(e) =>{
    e.preventDefault();
    axios.post("/addAppDetails", {
        pName: appData.pName, 
        appNum: appData.appNum, 
        datetime: appData.datetime, 
    })
    .then(res =>{
        console.log(res.appData)
    })
    .catch((error)=>{
        console.log(error);
      });
}


const handle = (e) => {
    const newData={...appData}
    newData[e.target.id] = e.target.value
    setAppData(newData)
    console.log(newData)
}

    return(
        <Form onSubmit={(e) => submit(e)}>
            <Form.Group>
                <Form.Control
                id="pName"
                type="text"
                placeholder="Patient Name"
                onChange={(e) => handle(e)}
                value={appData.pName}
                required/>
            </Form.Group>
            <Form.Group>
                <Form.Control
                id="appNum"
                type="text"
                placeholder="Appointment Number"
                onChange={(e) => handle(e)}
                required/>
            </Form.Group>
            <Form.Group>
                <Form.Control
                id="datetime"
                as="textarea"
                placeholder="Date and Time"
                onChange={(e) => handle(e)}
                required/>
            </Form.Group>

            <Button variant="success" type="submit" block>Update Appointment</Button>
        </Form>
    )
}

export default AddForm;

This is my backend, it contains the route/api for functionality

server.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

app.use(express.json()); //prints body request
app.use(cors());

const JWT_SECRET = "sdaikdhjiIHDiu8987J(@?!dDSF8645DAsadA[]ds54aASD()21asd1SFP";
const mongooseURL =
  "mongodb srv://client:[email protected]/?retryWrites=true&w=majority";

//server
app.listen(5001, () => {
  console.log("Server started successfully.");
});

//connect with DB
mongoose
  .connect(mongooseURL, {
    useNewUrlParser: true,
  })
  .then(() => {
    console.log("Connected to database successfully");
  })
  .catch((e) => console.log(e));

require("./models/appointmentDetails");
const AppDetails = mongoose.model("AppointmentDetails");

//add data to db
app.post("/addAppDetails", async(req, res) => {

  const newAppDetails = new AppDetails(req.body);

  try{
      newAppDetails.save();
      res.send(newAppDetails);
  }
  catch(err){
      console.log(err);
      res.status(500).send(error);
  }
});

This is my database model.

appointmentDetails.js

const AppDetails = new mongoose.Schema(
    {
        pName: String,
        appNum: String,
        datetime: String,
        status: String,
        action: String,
    },
    {
        collection: "AppointmentDetails",
    }
);

mongoose.model("AppointmentDetails", AppDetails);

CodePudding user response:

short answer

add baseURL

long answer

baseURL required for Axios

const submit = (e) => {
  e.preventDefault();
  axios
    .post(
      '/addAppDetails',
      {
        pName: appData.pName,
        appNum: appData.appNum,
        datetime: appData.datetime,
      },
      {
        baseURL: 'http://localhost:5001', // or your hosting server
      }
    )
    .then((res) => {
      console.log(res.appData);
    })
    .catch((error) => {
      console.log(error);
    });
};

But the method above is cumbersome because you have to set baseURL all the time. so make custom configured axios instance and use it globally.

// ./lib/axios.js  or whatever
export const axiosClient = axios.create({
  baseURL: process.env.MY_API_SERVER_URL || 'http://localhost:5001',
  headers: {
    // whatever you want to add to the headers
  },
  // and whatever your server requires
});
// just use your code with replacing axios to custom axios instance
axiosClient.post('/addAppDetails', {
  pName: appData.pName,
  appNum: appData.appNum,
  datetime: appData.datetime,
})

CodePudding user response:

404 means the url (including http://host:port) that you are using to send request & expecting response from, doesn't exist in your case.

While sending request, check if your node server is receiving the response or not, using logs, or a global middleware function logging every request info. This way you'll see whether the server is receiving the request or not, and thus find the problem.

As suggested in the answer by @thillon, most likely in your case the url is incomplete (doesn't contain the server's host:port part), so you can follow their way to ensure that your request url is proper and thus make sure that your server is able to receive request is this particular case.

Global middleware function

Write this right after your app.use(express.json()) statement.

app.use((req, res, next) => {
    console.log(req.body)
    // or log anything helpful in the req object
    next();
})
  • Related