Home > Net >  node js post 404 not found with router
node js post 404 not found with router

Time:09-13

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;

CodePudding user response:

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

CodePudding user response:

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
})
  • Related