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~! :)
Related
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
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!`);
});
enter image description here[
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
const app = express();
// Start up an instance of app
const PORT = 8080;
app.listen(PORT, () => {
console.log('Hi');
console.log(`the port that we will use is ${port}`);
});
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
app.post('/link', function(req,res) {
});
What should i do to run this in terminal
*I tried alot of solutions bot it's not working
in the terminal[
1.
it can not find the file
]3*
I think you need to install the 'body-parser' library and send it to call in your file
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
You don't need to use bodyparser if you use latest or after 4.0 version of Express.js. You can use
app.use(express.json()) // Parse Json Bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies
as middlewares instead, without any package. They will solve your problem.
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.
I have images in /public folder and I want to show them..simply like this: <img src="a.jpg">
My app.js code
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(8080);
app.use('/public', express.static(__dirname + "/public"));
If I open it in localhost this error is still showing
NetworkError: 404 Not Found - http://localhost:8080/public/a.jpg"
in your case it is enough to write:
app.use(express.static('public'));
it will serve directly the public folder.
an image in this path /public/images/somePhoto.png would be shown like that: http://localhost:8080/images/somePhoto.png
source: https://expressjs.com/en/starter/static-files.html
You need to drop the /public/ bit from your URL to your image.
So it becomes just http://localhost:8080/a.jpg
handling static files in express
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly.
For example, if you keep your assests in a folder called public, you can use
app.use(express.static('public')) as follows, my images are in public\images
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
save the code above to server.js
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and image will show up