[SOLVED] I can’t access image after upload with used app.use(express.static(__dirname, ‘public’));

Issue

This Content is from Stack Overflow. Question asked by wavesico

I can’t access image after upload with used app.use(express.static(__dirname, ‘public’));

how fix, Cannot GET /public/Screenshot-2022-09-13%20193207.jpg-1663505928511.jpeg

const app = express();
app.use(cors());
app.options("*", cors());

const api = process.env.API_URL
//http://localhost:5000/api/v1/products

//middlewares
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());
app.use(helmet());
app.use(morgan("tiny"));
const path = require('path');

// set static folder
app.set(express.static(path.join(__dirname, 'public')));
//app.use(authJwt()); 


app.use("/api/v1/products", productRoute);
app.use("/api/v1/users", userRoute);
app.use("/api/v1/categories", categoriesRoute);
app.use("/api/v1/orders", orderRoute);
app.use("/api/v1/uploading", excelImporRoute);

module.exports = app;



Solution

You’re using app.set() when you should be using app.use():

app.use(express.static(path.join(__dirname, 'public')));

Also, as @moonwave99 is already alluding to in their comment, the way you’re configuring the static middleware will cause static files to be accessible from the root of your website, not from /public. If you want the latter, use this:

app.use('/public', express.static(path.join(__dirname, 'public')));


This Question was asked in StackOverflow by wavesico and Answered by robertklep It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?