So, I am trying to access images from my uploads folder but getting following error:
I have added express.static(root, [options])
to my server.js here is the source code.
require("dotenv").config({
path: "C:/Users/dogra/Documents/Web Development/Portfolio/FullStack/market/.env",
});
const path = require("path");
const express = require("express");
const connectDB = require("./config/db");
connectDB();
const app = express();
app.use(express.json());
// Express Static Middleware
const staticPath = path.join(__dirname, "../uploads");
app.use(express.static(staticPath));
// Routes
const productRoutes = require("./routes/productRoutes");
const userRoutes = require("./routes/userRoutes");
const orderRoutes = require("./routes/orderRoutes");
const uploadRoutes = require("./routes/uploadRoutes");
app.use("/api", productRoutes);
app.use("/api/users", userRoutes);
app.use("/api/orders", orderRoutes);
app.use("/api/upload", uploadRoutes);
app.get("/api/config/paypal", (req, res) =>
res.send(process.env.PAYPAL_CLIENT_ID)
);
// uploads to "/uploads" folder
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));
// Check's If the route is not defined and passes 404 error
app.use((req, res, next) => {
const error = new Error(`Requested URL: ${req.path} not found!`);
error.status = 404;
next(error);
});
// Error handler
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
success: false,
status: error.status || 500,
message: error.message,
},
});
});
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`)
);
My file directory looks like this:
Also, I console.log staticPath
it is pointing to right directory. What I am doing wrong? Please Help. Thanks in advance.
Your path is still pointing to the wrong file. Log the path and see by yourself:
console.log('static path:', path.join(__dirname, "/uploads"))
So you have to write path.join(__dirname, "../uploads"))
since __dirname
will resolve to the ./server
directory.
You did that in the lines above but i guess the second call of express.static()
has overwritten the uploads
static path.
So this should work:
app.use('/uploads', express.static(path.join(__dirname, '../uploads'));
Maybe you want to use process.cwd()
. It always points to the location the program is started, so if you start your program via npm start
then process.cwd()
will always point to the directory the package.json
is located!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.