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
Related
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!`);
});
My Vue app runs perfectly on desktop, but on mobile, it fails to fetch data when the app loads, leaving the components rendering but with no data to display.
Link to the app
Link to the entire Github repository
I diagnosed the issue by running it through Google's Mobile-Friendly Test tool: here are the results.
My index.js looks like this:
const express = require("express");
const serveStatic = require("serve-static");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("./queries");
const app = express();
app.use(serveStatic(__dirname + "/dist"));
app.use(cors());
app.use(bodyParser.json());
app.get("/sizemenudata", db.getSizeMenuData);
app.get("/lightlevelmenudata", db.getLightLevelMenuData);
app.get("/easeofcaremenudata", db.getEaseOfCareMenuData);
app.get("/petsafemenudata", db.getPetSafeMenuData);
app.get("/menuTitles", db.getMenuTitles);
app.use(express.static("dist"));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
Things to note:
I'm fetching the data from a postgres database, here is my sql file.
I have a seperate queries.js file which I import into index.js.
Closing this because it was a simple error, the Heroku ENV vars weren't set.
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
I have an app.js script that contains an express node website
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('public'));
…
app.listen(3000, function () {
console.log('avalaible at http://localhost:3000');
});
until now I launch website by writing in cmd
node ./app.js
Then I go to adress http://localhost:3000 in my browser
I would have a batch or another way to those operations just by doucle click on a file
Could you help me please?
In the Node js project folder create a .bat file and put this on it:
node ./app.js
start "" http://localhost:3000
when you click the file this should launch your nodejs app and open your default browser on the given address.
hello i'm beginner express. before ask question, i'm sorry about my english
i make a sample express code & file structure
-I-bin(folder) - www.js
I
I-public(folder) - index.html
I
I-index.js
and code is like that
www.js is
let debug = require('debug')('example-server')
let app = require('../')
app.set('port', process.env.PORT || 3000)
let server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port)
})
index.js is
let express = require('express')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let app = express()
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
... below code just routing code...
but if i connect on localhost:3000 is render page in index.html
None of the above code sets the path to index.html.
Other example code uses the 'render' function, but not in this sample code. Why is my index example code showing index.html?
thank you~! :)