skip to Main Content

In my nodejs server file, I am trying to server static folder the code goes as below :-

server.js

const express = require("express");
const app = express();
require("dotenv").config();
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { connectDB } = require("./config/connectDB");
connectDB();
const upload = require("./routes/uploadsFile");
const user = require("./routes/user");
const path = require("path");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.json("content-type", "application/json"));

const publicFolder = path.join(__dirname, "../uploads");
console.log(publicFolder);
app.use(express.static(publicFolder));

app.use("/api/v1/upload", upload);
app.use("/api/v1/user", user);

const PORT = process.env.PORT || 3030;
app.listen(PORT, () => {
  console.log(`Server Started Listening On PORT ${PORT}`);
});

The folder structures goes below :-

This is the ss of my folder structure

The same error I am getting as everyone

Cannot GET /uploads/image/actual-size/banner-Image-1.jpg

Can someone please help me. I have gone through many problem already answered like this on Stackoverflow, but unable to get the proper solution.

2

Answers


  1. Chosen as BEST ANSWER

    I got the solution of the problem.

    I was calling the GET URL by

    localhost:${port}/uploads/image/actual-size/image.jpg
    

    But I had to call like this because uploads folder is being server by default

    localhost:${port}/image/actual-size/image.jpg
    

  2. You defined uploads to be the root directory for serving static files which means the request paths must not start with /uploads. In your example above change the path to:

    /image/actual-size/banner-Image-1.jpg

    From the docs:

    Express looks up the files relative to the static directory, so the
    name of the static directory is not part of the URL.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search