I'm learning node js and I get this error when I'm trying to get my data or add something the router doesn't work and I'm lost I don't see where the problem is. in my cmder, there is no problem it says connection to the server, and the DB is successful. this is my connectDB file:
const mongoose = require('mongoose')
const URI = process.env.DATABASE;
mongoose.connect(URI, { useUnifiedTopology: true } )
.then(()=>console.log("connect"))
.catch((error)=> console.log(error)) ;
and this is my index.js file:
const express = require('express')
const app = express()
const port = 3000
require("dotenv").config({path:".env"})
const bodyParser=require("body-parser")
const products = require('./Routes/products')
//connect to the database
require("./ConnectDB");
//middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//routes
app.use('/products',products);
//server
app.listen(port,() => {
console.log(`listen to http://localhost:${port}`)
})
This is my controller:
const Product=require('../Models/Product')
exports.getProducts=async(req,res)=>{
try{
console.log("requete",req.body)
const products=await Product.find()
res.send(products)
}
catch(error){
console.log(error)
}
}
exports.addProduct=async(req,res)=>{
try{
console.log("requete",req.body)
const product= await new Product(req.body).save()
res.send(product)
}
catch(error){
console.log(error)
}
}
exports.updateProduct=async(req,res)=>{
try{
const product=await Product.findOneAndUpdate({_id:req.params.productId},{ $set: req.body },
{ new: true })
res.send(product)
}
catch{
console.log(error)
}
}
exports.deleteProduct=async(req,res)=>{
try{
const product=await Product.findOneAndRemove({_id:req.params.productId})
res.send(product)
}
catch(error){
console.log(error)
}
}
and this is my routes file:
const express =require('express')
const router= express.Router()
const {getProducts,addProduct,updateProduct,deleteProduct}=require('../Controllers/product')
router.get("/",getProducts)
router.post("/new",addProduct)
router.put("/:productId",updateProduct)
router.delete("/:productId",deleteProduct)
module.exports = router
and this is my model:
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name:{
type:String,
required: true
}
});
const Product = mongoose.model('Product', productSchema);
module.exports=Product
when I enter http://localhost:3000/ I get this error " cannot GET / " or when I enter http://localhost:3000/?name=test I get the same problem with POST. if anyone knows what I did wrong I appreciate it thank you in advance. this is my project structure :
CodePudding user response:
You've mounted your router under /products
. So your requests should contain products
as their base-url , e.g:
http://localhost:3000/products