Throwing 404 Error with message "Cannot POST /api/users/register"

Viewed 1675

The main problem is here --> cant go through proxy - don't know why gave all the routes and checked them correctly but overall still not working Even though I can use cors and try directly but not sure why cant I use this method to perform the action ?

I am trying to register the user and send the data to MongoDB but it is not allowing it ? can you please give a suggestion? thanks

 POST http://localhost:3000/api/users/register 404 (Not Found)
 Error: Request failed with status code 404
     at createError (createError.js:16)
     at settle (settle.js:17)
     at XMLHttpRequest.onloadend (xhr.js:66)
 ```
 
 frontend part- I am using for react 
 
 ```import React, { useState, useEffect } from "react";
 
 import axios from "axios";
 import Error from "../components/Error";
 import Loader from "../components/Loader";
 import Success from '../components/Success'
 export default function Registerscreen() {
   const [name, setname] = useState("");
   const [email, setemail] = useState("");
   const [password, setpassword] = useState("");
   const [cpassword, setcpassword] = useState("");
   const[loading, setloading]=useState(false)
   const[error, seterror]=useState(false)
   const[success, setsuccess]=useState(false) 
   async function register(){
 
       if(password!=cpassword)
       {
           alert("passwords not matched")
       }
       else{
           const user={
               name,
               email,
               password
           }
           
           try {
             setloading(true)
             const result = await axios.post('/api/users/register',user)
             setloading(false)
             setsuccess(true)
             setemail('')
             setname('')
             setcpassword('')
             setpassword('')
           } catch (error) {
             seterror(true)
             setloading(false)
             console.log(error);
           }
       
       }
 
   }
 
   return (
     <div className='register'>
       <div className="row justify-content-center mt-5">
         <div className="col-md-5 mt-5 text-left shadow-lg p-3 mb-5 bg-white rounded">
 
           {loading && (<Loader/>)}
           {success && (<Success success='User Registered Successfully' />)}
           {error && (<Error error='Email already registred' />)}
 
           <h2 className="text-center m-2" style={{ fontSize: "35px" }}>
             Register
           </h2>
           <div>
             <input required type="text" placeholder="name" className="form-control mt-1" value={name} onChange={(e)=>{setname(e.target.value)}} />
             <input required type="text" placeholder="email" className="form-control mt-1" value={email} onChange={(e)=>{setemail(e.target.value)}} />
             <input
               type="text"
               placeholder="password"
               className="form-control mt-1"
               value={password}
               required
               onChange={(e)=>{setpassword(e.target.value)}}
             />
             <input
               type="text"
               placeholder="confirm password"
               className="form-control mt-1"
               value={cpassword}
               required
               onChange={(e)=>{setcpassword(e.target.value)}}
             />
             <button onClick={register} className="btn btn-primary rounded-pill mt-3 mb-3">REGISTER</button>
             <br/>
             <a style={{color:'black'}} href="/login">Click Here To Login</a>
           </div>
         </div>
       </div>
     </div>
   );
 }
 ```
 pacakage.json- where I gave a proxy and trying to make it work
 ```,
   "browserslist": {
     "production": [
       ">0.2%",
       "not dead",
       "not op_mini all"
     ],
     "development": [
       "last 1 chrome version",
       "last 1 firefox version",
       "last 1 safari version"
     ]
   },
   "proxy": "http://localhost:5000/"
 }
 ```
 
 usersroute- defined all the routes 


 ```const express = require("express");
 const router = express.Router();
 // express router 
 const User = require("../models/user")
 //import the user model 
 
 router.post("/register", async(req, res) => {
   
 
     const newUser = new User({name: req.body.name , email: req.body.email , password: req.body.password})
 
     try {
         const user = await newUser.save()
         // save the user 
         res.send('User Registered successfully')
     } catch (error) {
          return res.status(400).json({ message: error });
     }
 
 });
 
 
 router.post("/login", async(req, res) => {
 
     const {email , password} = req.body
 
     try {
         
         const user = await User.findOne({email : email , password: password})
         // match the subset in a collection 
 
         if(user){
        
             res.send(currentUser);
         }
         else{
             return res.status(400).json({ message: 'User Login Failed' });
         }
 
     } catch (error) {
            return res.status(400).json({ message: 'Something went weong' });
     }
   
 });
 
 
 
 
 
 
 module.exports = router
 ```
 
 
 server.js---- server file where I gave all the routes 
 ```
 const express = require("express");
 
 const app = express();
 
 
       bodyParser = require('body-parser');
 
 // support parsing of application/json type post data
 app.use(bodyParser.json());
 
 //support parsing of application/x-www-form-urlencoded post data
 app.use(bodyParser.urlencoded({ extended: true }));
 
 
 
 const dbConfig = require('./db')
 app.use(express.json())
 // import the rooms route 
 const roomsRoute = require('./routes/roomsRoute')
 const usersRoute = require('./routes/usersRoute')
 
 
 
 // access for the rooms route- to go and check the endpoints in rooms route- to fecth the rooms in database 
 app.use('/api/rooms', roomsRoute)
 app.use('api/users', usersRoute)
 
 
 const port = process.env.PORT || 5000;
 
 app.listen(port,() => console.log(`yayay Server running on port ${port}`));
 
 
 
 
 ```
 Userschema
 ```
 const mongoose = require("mongoose");
 
 const userSchema = mongoose.Schema({
     name : {
         type: String , 
         required: true
     },
     email : {
         type: String , 
         required: true
     },
     password : {
         type: String , 
         required: true
     },
     isAdmin : {
         type: Boolean  , 
         default: false
     }
 
 } , {
     timestamps : true,
     collection: 'users',
 })
 
 const userModel = mongoose.model('users', userSchema)
 module.exports = userModel
 ```
2 Answers

I dont think it is a configuration error or it is because of the proxy.

There is an error in your server.js file, where you mentioned the route request.

Please change the route to

app.use('/api/users', usersRoute)

instead of this

app.use('/api/rooms', roomsRoute)
app.use('api/users', usersRoute)

then the link the your trying to get will be passed as a post request to the back-end.

404- is syntax error. I would start by checking the syntax rather than the config file.

You've configured the API server to use port 5000 by default, and the frontend app is calling port 3000.

Make sure you're calling the API via the correct port number.

  • You can also try to change the API to a full URL if it's a proxy issue, like this
"proxy": {
    "/api/users": {
        "target": "http://localhost:5000"
    }
},
Related