СООБЩЕНИЕ http://localhost:3000/programare 404 (Не найдено)

#javascript #node.js #reactjs #mongodb #routes

Вопрос:

Я использую MongoDB, и когда я пытаюсь перенаправить бронирование с 6 входами в моем mongooDB, я получаю ошибку из названия. Здесь вы можете увидеть мои папки, вот мое бронирование .js

 import React from "react";
import Cutter from "../../../assets/images/Cutter.png";
import validate from "../validations/validateInfo";
import "./booking.css";
import { TimePickerComponent } from "@syncfusion/ej2-react-calendars";
import { useState, useEffect } from "react";
import axios from "axios";

const Booking = () => {
  const minTime: Date = new Date("01/02/2023 09:00 AM");
  const maxTime: Date = new Date("01/02/2023 5:00 PM");

  // const { handleChange, values, handleSubmit, errors } = useForm(validate);

  const [values, setValues] = useState({
    firstName: "",
    lastName: "",
    phoneNumber: "",
    email: "",
    date: "",
    hour: "",
  });

  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;

    setValues((prevValues) => {
      return { ...prevValues, [name]: value };
    });
  };

  const handleClick = (e) => {
    e.preventDefault();
    const newProgramare = {
      firstName: values.firstName,
      lastName: values.lastName,
      phoneNumber: values.phoneNumber,
      email: values.email,
      date: values.date,
      hour: values.hour,
    };

    axios.post("http://localhost:3000/programare", newProgramare);
  };

  return (
    <div className="programaree">
      <div className="wrapper-icon">
        <div className="line"></div>
        <img src={Cutter} className="scissors" />
        <div className="line"></div>
      </div>
      <div className="booking-text">
        <h1 className="title-servicii">PROGRAMARE ONLINE</h1>
        <h4 className="subtitle-servicii">
          Ne incadram in ora programata de tine si respectam programul de tuns
        </h4>
      </div>
      <div className="container">
        <div className="left-container">
          <h2 className="title-design">PROGRAM DE LUCRU</h2>
          <div className="program">
            <div className="days">
              <h5 className="subtitle-booking">Luni-Sambata:</h5>
              <h5 className="subtitle-booking">Duminica:</h5>
            </div>
            <div className="hours">
              <h5 className="subtitle-booking">10:00 - 21:00</h5>
              <h5 className="subtitle-booking">10:00 - 16:00</h5>
            </div>
          </div>
          <h2 className="title-design">DATE DE CONTACT</h2>
          <div className="program">
            <div className="days">
              <h5 className="subtitle-booking">Telefon:</h5>
              <h5 className="subtitle-booking">Email:</h5>
            </div>
            <div className="hours">
              <h5 className="subtitle-booking">0746060270</h5>
              <h5 className="subtitle-booking">test@gmaiil.com</h5>
            </div>
          </div>
        </div>
        <div className="right-container">
          <form className="form">
            <div className="style-form">
              <div className="right-form">
                <div className="inputs">
                  <input
                    id="firstName"
                    className="input"
                    name="firstName"
                    placeholder="Numele mic"
                    type="text"
                    value={values.firstName}
                    onChange={handleChange}
                  ></input>
                  {errors.firstName amp;amp; <p>{errors.firstName}</p>}
                </div>
                <div className="inputs">
                  <input
                    id="lastName"
                    className="input"
                    name="lastName"
                    placeholder="Numele de familie"
                    type="text"
                    value={values.lastName}
                    onChange={handleChange}
                  ></input>
                  {errors.lastName amp;amp; <p>{errors.lastName}</p>}
                </div>
                <div className="inputs">
                  <input
                    id="phoneNumber"
                    className="input"
                    name="phoneNumber"
                    placeholder="Numar de telefon"
                    type="phoneNumber"
                    value={values.phoneNumber}
                    onChange={handleChange}
                  ></input>
                  {errors.phoneNumber amp;amp; <p>{errors.phoneNumber}</p>}
                </div>
              </div>
              <div className="right-form">
                <div className="inputs">
                  <input
                    id="email"
                    className="input"
                    name="email"
                    placeholder="Email"
                    type="Email"
                    value={values.email}
                    onChange={handleChange}
                  ></input>
                  {errors.email amp;amp; <p>{errors.email}</p>}
                </div>
                <div className="inputs">
                  <input
                    id="date"
                    className="input"
                    name="date"
                    placeholder="Date"
                    type="date"
                    value={values.date}
                    onChange={handleChange}
                  ></input>
                  {errors.date amp;amp; <p>{errors.date}</p>}
                </div>
                <div className="inputs-hour">
                  <TimePickerComponent
                    id="hour"
                    name="hour"
                    className="Hour"
                    placeholder="Alegeti-va ora"
                    min={minTime}
                    max={maxTime}
                    format="HH:mm"
                    step={45}
                    value={values.hour}
                    onChange={handleChange}
                  ></TimePickerComponent>
                  {errors.hour amp;amp; <p>{errors.hour}</p>}
                </div>
              </div>
            </div>
            <button className="button-form" type="submit" onClick={handleClick}>
              {" "}
              Programeaza-te
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Booking; 

Изображение с формой интерфейса Здесь

В server.js находится здесь:

 require("dotenv").config({ path: ".env" });
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const fileUpload = require("express-fileupload");

const app = express();
app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.use(
  fileUpload({
    useTempFiles: true,
  })
);

// Routes
app.use('/user', require('./routes/userRouter'))
app.use('/api', require('./routes/upload'))

//Connect to mongoodb

const URI = process.env.MONGODB_URL;
mongoose.connect(URI, (err) => {
  if (err) throw err;
  console.log("connected to MongoDB");
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log("Server is running on port", PORT);
}); 

And I do have app.use(‘/user’, require(‘./routes/userRouter’)) witch make link with my route from routes

Here is my route:

 router.route("/programare").post((req,res)=>{
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const phoneNumber = req.body.phoneNumber;
    const email = req.body.email;
    const date = req.body.date;
    const hour = req.body.hour;

    const newProgramare = new Prog({
        firstName,
        lastName,
        phoneNumber,
        email,
        date,
        hour
    })

    newProgramare.save();
})




module.exports = router; 

И моя схема-это программная схема, которую я использую :

 const mongoose = require("mongoose");

const programareSchema = {
  date: String,
  email: String,
  firstName: String,
  hour: String,
  lastName: String,
  phoneNumber: String,
};

const Prog = mongoose.model("Programare",programareSchema)

module.exports=Prog;

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please enter your name !"],
      trim: true,
    },
    email: {
      type: String,
      required: [true, "Please enter your email !"],
      trim: true,
      unique: true,
    },
    password: {
      type: String,
      required: [true, "Please enter your password !"],
    },
    role: {
      type: Number,
      default: 0, //0 = user , 1 = admin
    },
    avatar: {
      type: String,
      default:
        "https://www.google.ro/imgres?imgurl=https://www.w3schools.com/howto/img_avatar.pngamp;imgrefurl=https://www.w3schools.com/howto/howto_css_image_avatar.aspamp;tbnid=Jjq5a5o5G80fpMamp;vet=12ahUKEwj9uKXAi9ryAhVBxqQKHeSUCo0QMygAegUIARCyAQ..iamp;docid=IN--qpeX1hje-Mamp;w=499amp;h=498amp;q=avatar imageamp;hl=roamp;ved=2ahUKEwj9uKXAi9ryAhVBxqQKHeSUCo0QMygAegUIARCyAQ",
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Users", userSchema); 

Я хотел бы добавить свой объект в MongoDB, когда я нажимаю «Programeaza-te», но я получаю эту ошибку . Я хочу отметить, что я использую правильный локальный хост . Пожалуйста, помогите !

Ответ №1:

Путь /programare добавляется к маршруту, указанному в вашем server.js файле здесь:

 app.use('/user', require('./routes/userRouter'))
 

Это означает, что путь, который должен использовать интерфейс /user , равен /programare или /user/programare .

 // booking.js
axios.post("http://localhost:3000/user/programare", newProgramare);