Getting "Cannot GET /uploads/" for static file in Node js

Viewed 57
import express from "express";
import path from "path";
import cors from "cors";
import bodyParser from "body-parser";
import {fileURLToPath} from 'url';
import fileRoutes from "./routes/fileuploadRoutes.js"
const app = express();
app.use(cors());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// console.log((path.join(__dirname, 'uploads')))
app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

I Used the above code and not able to get the static uploads folder at "http://localhost:3000/uploads/" where 3000 is the port defined. enter image description here

3 Answers

Please that way is not correct .Using use method for getting your file is not correct .Instead use get method to get them . This way of writting is used to attach middleware to your express app and not used to get file . Replace app.use('/uploads', express.static(path.join(__dirname, '/uploads'))) by

app.use(express.static(path.join(__dirname, "uploads"))); // attaching middleware

then after get your file with :

app.get('/uploads' , function (req, res){
     res.send("<img src='your_file_name_in_uploads_folder'>")  //for example
})  // a endpoint that will handle your file uploading

can you please try once with the following code?

import express from "express";
import path from "path";
import cors from "cors";
import bodyParser from "body-parser";
import {fileURLToPath} from 'url';
import fileRoutes from "./routes/fileuploadRoutes.js"
const app = express();
app.use(cors());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// console.log((path.join(__dirname, 'uploads')))
app.use(bodyParser.json());
app.get('/uploads', express.static(path.join(__dirname, '/uploads')))

Got the answer, finally tried with axios api call

Related