skip to Main Content

Hello I am using POSTMAN to post and get api calls in JSON to a MONGODB Atlas database which is on a react project. I am getting the above error and I do not know where to start because I am new to using them. I have the drivers db in my localhost created using mongosh not sure if I should have it there as I am trying to connect to the drivers db in Atlas. I am making the call in POSTMAN using http://localhost:5000/drivers/add

//server.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
//app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
const driverRouter = require('./routes/driver'); 

app.use('/driver', driverRouter);
app.listen(port, () => {
 // perform a database connection when server starts
 dbo.connectToServer(function (err) {
   if (err) console.error(err);

 });
 console.log(`Server is running on port: ${port}`);
});
//route
const router= require('express').Router();
let Driver = require('../models/driver.model');

router.route('/').get((req, res) =>{
    Driver.find()
    .then(driver => res.json(driver))
    .catch(err => res.status(400).json('Error: '+ err));

}
)

router.route('/add').post((req, res) => {
    const name = req.body.name;
    const email = req.body.email;
    const phone = req.body.phone;
    const address = req.body.address;
    const country =req.body.country;
    const newDriver = new Driver({name, email, phone, address, country});
  
    newDriver.save()
      .then(() => res.json('Driver added!'))
      .catch(err => res.status(400).json('Error: ' + err));
  });
  
  module.exports = router; 
//model
const mongoose = require('mongoose');

const Schema= mongoose.Schema;

const driverSchema= new Schema({
   name:{type: String, required:true},
   email:{type: String, required:true},
   phone:{type: String, required:true},
   address:{type:String, required:true},
   country:{type: String, required:true}
});

const Driver= mongoose.model('Driver', driverSchema);

module.exports =Driver;

3

Answers


  1. You are making a request to http://localhost:5000/drivers/add, but your route is /driver, so just remove the s from drivers and make a request to http://localhost:5000/driver/add, then it should work.

    Login or Signup to reply.
  2. Change app.use("/driver", driverRouter) to app.use("/drivers", driverRouter)

    I added an "s" to driver

    Login or Signup to reply.
  3. You are making a request to /drivers, but your route is /driver, so just remove the s from drivers and make a request to http://localhost:5000/driver/add, then it should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search