skip to Main Content

hello i have a issue i build a project when i start to add the server side
i am using node js express
i create fetch post to spesific url from the database (mongoDB)
and i want to add the users
now
its workd but i try to reconfigure the files and using router and now i get 404 when i try to make the post is upload some code

just need to know where is the bad request
the url i want to fetch is
http://localhost:5000/shopping-cart/user/sign-up

    Axios.post("http://localhost:5000/shopping-cart/user/sign-up", user).then((response) => {
      console.log(response);
    });


const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path")
const productRouter = require("./routes/product.route");
const userRouter = require("./routes/user.route");
const { setServerConfiguration } = require("./config");

setServerConfiguration(app);
mongoose.connect('mongodb://localhost/shopping-cart-data-base');

app.use("/shopping-cart", productRouter);

app.use("/user/sign-up", userRouter);


app.listen(5000);

const router = require('express').Router();
const errorsHandler = require('../utils/errorsHandler');
const UserModel = require('../models/User');

router.post("/user/sign-up", async (req, res) => {
    let body = req.body;
    console.log(body)
    try{
        await UserModel.create({
            name: body.name,
            username: body.username,
            password: body.password,
            shoppingHistory: [],
          });
          res.send(body);
    }catch(e){
        return errorsHandler(e, req, res);
    }
});

module.exports = router;

3

Answers


  1. 404 route not found

    app.use("/shopping-cart", productRouter) => route1
    
    app.use("/user/sign-up", userRouter); => route2
    

    route1 other route2

    url http://localhost:5000/shopping-cart request route1

    url http://localhost:5000/user/sign-up request route2

    Login or Signup to reply.
  2. Try this url

    "http://localhost:5000/user/sign-up"
    

    If you want to use "http://localhost:5000/shopping-cart/user/sign-up" than you need to define route like that, for example:

    router.post("shopping-cart/user/sign-up", async (req, res) => {
    
    //Your code
    })
    
    Login or Signup to reply.
  3. Your router is mounted on the /user/sign-up prefix:

    app.use("/user/sign-up", userRouter);
    

    Which means that all requests that start with /user/sign-up will get passed to your router.

    Your router should be routing relative to that prefix, so to make it work, use this:

    router.post('/', ...)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search