Express Node js Невозможно получить доступ к файлам stati c в параметре маршрутизации. - PullRequest
0 голосов
/ 25 апреля 2020

При доступе к моему маршруту http://localhost: 3000 / product / detail отображается ошибка 404 для моих файлов stati c, но при посещении той же страницы с одним параметром маршрута, например http://localhost: 3000 / product отлично отображает все файлы * stati c. Вот ошибка при доступе с несколькими параметрами маршрута

var express = require("express");enter code here
var app = express();
var bodyParser = require("body-parser");//to convert string page to object from html page
var mongoose=require("mongoose");

mongoose.connect("mongodb://127.0.0.1/renclo",{useNewUrlParser:true,useUnifiedTopology:true});//connect database
//mongoose.connect("mongodb+srv://nik:nik@cluster0-5tolk.mongodb.net/test?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true});//connect database cloud

app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine","ejs");//to attach .ejs to every html page
app.use(express.static('public'));//to access images or other resources

var comment=require("./models/comment");
var product=require("./models/product");
var user=require("./models/user.js");
var passport=require("passport");//for Authentication
var localstratedy=require("passport-local");
var passportlocalmongoose=require("passport-local-mongoose");
var expresssession=require("express-session");
var methodoverride=require("method-override")//for using put delete as method
app.use(methodoverride("_method"));
var flash=require("connect-flash")
app.use(flash());

mongoose.set("useCreateIndex",true);
///////////////Authentication///////////////////////////////
app.use(expresssession({//to encode                       //
  secret:"i am the best coder",                           //
  resave:false,                                           //
  saveUninitialized:false                                 //
}));                                                      //
                                                          //
app.use(passport.initialize());//to initialize passport   //
app.use(passport.session()); //to create session in pages //
passport.use(new localstratedy(user.authenticate()));     //to use local as localstrategy
passport.serializeUser(user.serializeUser());             //decode
passport.deserializeUser(user.deserializeUser());         //encode
                                                          //
////////////////////////////////////////////////////////////
app.use(function (req,res ,next) {//to pass userinformation in every page
  res.locals.currentuser=req.user//sets currrent user if its empty sets undefined
  res.locals.error=req.flash("error");//sets error and if its empty sets []
  res.locals.success=req.flash("success");
  next();
})
/////////////Routes////////////////////////////////////////
app.get("/product/:detail", function(req, res,next){
  res.render("productdetail");
});
app.get("/", function(req, res){//landing page
    res.render("index");
});
app.get("/about", function(req, res){//about page
    res.render("about");
});
app.get("/contact", function(req, res){//contact page
    res.render("contact");
});
app.get("/register", function(req, res){//contact page
    res.render("account");
});
app.post("/register",function(req,res){//register page
  var newuser=new user({username:req.body.username,fullname:req.body.fullname,email:req.body.email,code:req.body.code,phoneno:req.body.phoneno})
  if(req.body.code==="teranaam"){
newuser.isadmin=true;
  }
  user.register(newuser,req.body.password,function(error,usersaved){//registering new user
    if (error) {
      req.flash("error",error.message)
      res.redirect("/register")
    }else{

      passport.authenticate("local")(req,res,function(){//crating sessions
        req.flash("success","successfully signed up")
        res.redirect("/")
      })
    }
  })
});
app.post("/login",passport.authenticate("local",{successRedirect:"/",failureRedirect:"/",failureFlash:"Username or Password Incorrect",successFlash:"LoggedIn successfully"}),function (req,res) {//authenticating

});
app.get("/logout",function (req,res) {
req.logout()//function to logout
req.flash("success","Logged out!!")
res.redirect("/");
});
app.post("/newproduct",function(req,res){
  console.log(req.body.description);
  var newproduct={tag:req.body.tag,title:req.body.title,rating:req.body.rating,disc:req.body.disc,price:req.body.price,image:req.body.image,category:req.body.category}
product.create(newproduct,function(error,savedproduct){
  if (error) {
    console.log(error);
  }else{
    req.flash("success","added product")
    res.redirect("/product")
  }
})

});
app.get("/newproduct", function(req, res){//contact page
    res.render("newproduct");
});
app.get("/product", function(req, res){// all campgrounds page
  product.find({},function(error,retrivedproduct){
    if (error) {
console.log(error);
}else {
  res.render("product",{retrivedproduct:retrivedproduct});//sending datatbase file to page
}
});
});
// app.get("/product/:id", function(req, res){
//   var productpid=req.params.id;
//   product.findById(productid).populate("comment").exec(function(error,searchedproduct) {
//     if (error) {
//       console.log("error!!!!!!"+error);
//     }else {
//       res.render("product-detail.ejs",{respectiveproduct:searchedproduct});
//     }
//   })
//
// });

app.delete("/delete/:id",function(req,res){
  console.log(req.params.id);
  product.findByIdAndRemove(req.params.id,function(error){//for deleting
    if (error) {
      res.redirect("error")
    }else{

      res.redirect("/product")
    }
  })
});

//var port=process.env.PORT||3000;//to work in heroku server`enter code here`
app.listen(3000, function(){//listens to port 3000
   console.log("the Renclo server started!...");
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...