如何解决使用multer上传图像并公开上传但在诸如 localhost:3000/listing/condo 之类的路线中没有显示图像
需要软件包:
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const FacebookStrategy = require("passport-facebook").Strategy;
const findOrCreate = require("mongoose-findorcreate");
const path = require("path");
设置multer:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req,file,cb) {
cb(null,"./upload/");
},filename: function (req,new Date().toISOString() + file.originalname);
},});
const upload = multer({ storage: storage });
设置 ejs:
app.set("view engene","ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
使用护照会话:
app.use(
session({
secret: process.env.SECRET,resave: false,saveUninitialized: false,})
);
app.use(passport.initialize());
app.use(passport.session());
设置 mongo 数据库:
mongoose.connect("mongodb://localhost:27017/homeDB",{
useNewUrlParser: true,useUnifiedTopology: true,});
mongoose.set("useCreateIndex",true);
const userSchema = new mongoose.Schema({
email: String,username: String,fullname: String,phone: String,role: String,password: String,profileimg: String,googleId: String,facebookId: String,houseId: [String],});
const houseSchema = new mongoose.Schema({
ownerId: String,ownername: String,ownerphone: String,ownerdp: String,renterId: String,title: String,status: String,city: String,price: String,paymentStatus: String,reviews: [
{
name: String,comments: String,rating: String,},],rooms: String,births: String,area: String,areacode: String,address: String,type: String,renters: String,housedp: String,housepics: [String],speciality: String,});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User",userSchema);
const House = new mongoose.model("House",houseSchema);
passport.use(User.createStrategy());
passport.serializeUser(function (user,done) {
done(null,user.id);
});
passport.deserializeUser(function (id,done) {
User.findById(id,function (err,user) {
done(err,user);
});
});
谷歌 OAuth:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,clientSecret: process.env.CLIENT_SECRET,callbackURL: "http://localhost:3000/auth/google/home",userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",function (accesstoken,refreshToken,profile,cb) {
User.findOrCreate(
{ googleId: profile.id,username: profile.displayName },user) {
return cb(err,user);
}
);
}
)
);
Facebook OAuth:
passport.use(
new FacebookStrategy(
{
clientID: process.env.APP_ID,clientSecret: process.env.APP_SECRET,callbackURL: "http://localhost:3000/auth/facebook/home",cb) {
User.findOrCreate(
{ facebookId: profile.id,user);
}
);
}
)
);
app.use("/upload",express.static("upload"));
app.get("/",(req,res) => {
res.render("index.ejs");
});
app.post("/",upload.single("profileimg"),res) => {
console.log(req.file);
User.register(
{
username: req.body.username,fullname: req.body.fullname,phone: req.body.phone,email: req.body.useremail,role: req.body.role,profileimg: req.file.path,req.body.password,(err,user) => {
if (err) {
console.log(err);
res.redirect("/");
} else {
passport.authenticate("local")(req,res,() => {
res.redirect("/home");
});
}
}
);
});
app.get("/home",res) => {
if (req.isAuthenticated()) {
User.findById({ _id: req.user.id },foundusers) => {
if (err) {
console.log(err);
} else {
if (foundusers) {
House.find({},foundhouses) => {
if (foundhouses.length != 0) {
console.log(foundhouses);
const username = foundusers.username;
const profileDp = foundusers.profileimg;
const role = foundusers.role;
res.render("home.ejs",{
Housedbstatus: foundhouses.length,userdisplayname: username,profileimage: profileDp,userRole: role,houses: foundhouses,// houseImage: foundhouse.housedp,// prices: foundhouse.price,// listerimage: foundowner.profileimg,// housetitle: foundhouse.title,// address: foundhouse.price,// area: foundhouse.area,// city: foundhouse.area,// housenumber: foundhouse.address,// rooms: foundhouse.rooms,// births: foundhouse.births,// renters: foundhouse.renters,// type: foundhouse.type,// listername: foundowner.fullname,});
} else if (foundhouses.length == 0) {
console.log("no houses");
console.log("user" + req.user);
const username = foundusers.username;
const profileDp = foundusers.profileimg;
const role = foundusers.role;
res.render("home.ejs",});
}
});
}
}
});
} else {
res.redirect("/");
}
});
app.post("/login",res) => {
const user = new User({
username: req.body.username,password: req.body.password,});
req.login(user,(err) => {
if (err) {
console.log(err);
res.redirect("/");
} else {
passport.authenticate("local")(req,() => {
res.redirect("/home");
});
}
});
});
app.get(
"/auth/google",passport.authenticate("google",{ scope: ["profile"] })
);
app.get(
"/auth/google/home",{ failureRedirect: "/" }),res) => {
res.redirect("/home");
}
);
app.get("/auth/facebook",passport.authenticate("facebook"));
app.get(
"/auth/facebook/home",passport.authenticate("facebook",function (req,res) {
// Successful authentication,redirect home.
res.redirect("/home");
}
);
app.get("/listing",foundusers) => {
if (err) {
console.log(err);
} else {
if (foundusers) {
console.log(foundusers);
const username = foundusers.username;
const profileDp = foundusers.profileimg;
const role = foundusers.role;
res.render("listing.ejs",{
userdisplayname: username,});
}
}
});
} else {
res.redirect("/");
}
});
现在这是图像不会改变 URL 的地方,而是 pf localhost:3000/imagepath 它包含 ipe localhost:3000/listing/imagepath 的列表路径
app.get("/listing/:housetype",foundusers) => {
if (err) {
console.log(err);
} else {
if (foundusers) {
console.log(foundusers);
const username = foundusers.username;
const profileDp = foundusers.profileimg;
const role = foundusers.role;
res.render("Appartment.ejs",});
}
}
});
} else {
res.redirect("/");
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。