Home > database >  Express.js, getting 404 (Not Found) error for my newly added route
Express.js, getting 404 (Not Found) error for my newly added route

Time:06-26

I am having some issues while creating second route on my project. While router.get("/getallrooms") works just fine, router.post("/getroombyid") is giving me 404 not found message:

POST http://localhost:3000/book/api/rooms/getroombyid 404 (Not Found)

I have attached my routes code, Booking screen, where I am trying to use this getroombyid route and the server.js code. I will gladly accept any suggestions.

const express = require('express');
const router = express.Router();

const Room = require('../models/room')


router.get("/getallrooms", async(req, res) =>{

    try{
        const rooms = await Room.find({})
        res.send(rooms)
    }
    catch(error){
        return res.status(400).json({message: error});
    }
});

router.post("/getroombyid", async(req, res) => {
    const roomid = req.body.roomid
    try {
         const room = await Room.findOne({'_id' : req.body.roomid})
         res.send(room)
    } catch (error) {
         return res.status(400).json({ message: error });
    }
});

module.exports = router

Bookingscreen

import React, {useState, useEffect} from 'react'
import axios from 'axios'

function Bookingscreen({match}) {

  const [loading, setloading] = useState()
  const [error, seterror] = useState()
  const [room, setroom] = useState()

  useEffect(() => {
    try {
        setloading(true)
        async function gettingRoom() {
            const data = (await axios.post('./api/rooms/getroombyid', {roomid : match.params.roomid})).data
            setroom(data)
            setloading(false)
        }
        gettingRoom()
    }
    catch (error) {
        seterror(true)
        console.log(error)
        setloading(false)
    }
  }, [])

  return (
    <div>
        <h1>Bookingscreen</h1>
        <h1>Room id = {match.params.roomid}</h1>
    </div>
  )
}

export default Bookingscreen

server.js

const express = require("express");

const app = express();
const dbConfig = require('./db')

const roomsRoute = require('./routes/roomsRoute')
app.use(express.json())
app.use('/api/rooms', roomsRoute)

const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`App listening on port ${port}`)
});

CodePudding user response:

The problem is caused by the below line, specifically the ./api part:

const data = (await axios.post('./api/rooms/getroombyid', {roomid : match.params.roomid})).data

What you are doing is taking into account your current url inside the browser, which I assume is /book, so the final request is made to:

http://localhost:3000/book/api/rooms/getroombyid

Which doesn't exist on your back end. Change the above line with this one:

const data = (await axios.post('/api/rooms/getroombyid', {roomid : match.params.roomid})).data
  • Related