Node.js - Exposing Uploaded File - node.js

I'm building a nodejs express webapp:
const express = require("express");
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express();
app.use(express.json({limit: '100mb'}));
app.use(express.urlencoded({ limit: '100mb',extended: true }));
in it I'm trying to upload an image and show it in the next page.
I'm using multer to upload the file and move it to a subdirectory of my public static folder I have set in express.
const path = require("path");
app.use("/static", express.static(path.join(__dirname, "public")));
That part works, the file is properly uploaded and moved, however when I try and access the image I get an error message:
Cannot GET /static/uploads/1/1655219221091/cover/Screenshot%202022-05-24%20at%2016.44.45.png
any clue to what I might be doing wrong? anyone else experiencing this? should I create a custom route to serve these files that technically aren't static?
linking it in html returns a 404
thanks

Related

Serving Static file publically in nodejs :- Not Working

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 :-
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.
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.
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

How to send css files with express js

I am having a hard time sending css files with express. The way my project is structured is I have a src folder and inside the src folder is the app.js for the express code as well as another folder titled "public". Inside of this public folder I have an experience.html page as well as an experience.css page. I can only get the html to render on the page and cannot get the css styling to show up. Attached is my code for the app.js page.
const express = require('express');
const app = express ();
const port = process.env.Port || 3000;
app.get('/experience', (req, res) => {
res.sendFile(__dirname+'/public/experience.html');
})
app.use(express.static('/public/experience.css'))
app.listen(port);
Just using middleware is enough, you don't need dedicated get routes to the files unless you want to mask some of the filenames.
This should work for your case
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
You can access them on http://localhost:3000/experience.html, http://localhost:3000/experience.css
You can use the Express static middleware with the path to the public folder.
Once you do that, you can expose a route to the files (or) you can access at localhost:9900
//Import modules
const express = require("express");
const path = require("path");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, (err) => {
console.log(`Your dog server is up and running!`);
});

Node + Express how to access to upload folder

I built an upload in my API using multer that works perfectly.
I'm trying to access at the uploaded files from Gatsby but it doesn't work
router.use("/public", express.static(__dirname + "/public"));
The files are in /public/uploads :
http://localhost:5000/public/uploads/364935-2020-08-18.jpg
but I can't access them.
I tried different sintaxs:
router.use("/public", express.static(__dirname + "/public"));
router.use(express.static(__dirname + "/public"));
router.use(express.static("public"));
no one worked
Any idea?
Thanks
Trying Node's built-in path module:
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "public")));

npm run build cannot find index.html in public subfolder

I continue to get the error below when I try to build a production version of my app. Npm run build is looking for my index.html file in public, but it thinks my public folder is in my root directory whereas it is in the client subfolder.
Could not find a required file.
Name: index.html
Searched in: C:\Users\wharfchillin\wharf-chillin-app\public
My public folder is located in a sub-folder of my app:
client
--->public
------>index.html
I have tried to make this clear in my server.js file in numerous ways:
UPDATED
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const path = require('path');
const users = require("./routes/api/users");
const plaid = require("./routes/api/plaid");
const app = express();
const publicPath = path.resolve(__dirname);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(publicPath));
app.use('*', (req, res) => {
res.sendFile(path.resolve(publicPath));
});
// production mode
if(process.env.NODE_ENV === 'production')
app.use(express.static(path.resolve(publicPath)));
console.log('test')
console.log(publicPath)
Any advice would be more than appreciated.
You are using window os, window os's path use backward slash, but in your node app, you are define the path using forward slash, node has api to handle this, path.resolve. Stop using path.join

Getting issue with upload file using multer

Uploading file using multer, here is my code
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
app.post("/upload",upload.single('image'), api.uploadFile);
getting following error when uploading image file doing multi-part request
Error: Buffer.write(string, encoding, offset[, length]) is no longer supported
at Buffer.write (buffer.js:742:11)
at MultipartParser.initWithBoundary (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\multipart_parser.js:61:17)
at IncomingForm._initMultipart (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:308:10)
at IncomingForm._parseContentType (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:250:12)
at IncomingForm.writeHeaders (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:129:8)
at IncomingForm.parse (D:\eclipse-workspace-oxy\ChatServer\node_modules\formidable\lib\incoming_form.js:97:8)
at D:\eclipse-workspace-oxy\ChatServer\node_modules\connect\lib\middleware\multipart.js:125:12
Your stack trace shows that the problem comes from formidable, not multer.
A quick search on formidable's github open issues gives this.
Maybe try to run npm update.
Finally got the solution, need to add bodyParser for parse request bodies in a middleware.
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
it will work for Url Encoded requests. For Multi-part request, need to add middle ware like multer.

Resources