I have put images inside "/public/images" path. Now in the respose I am getting url as I wanted. But as soon as I paste that url to web browser, it says Cannot GET /public/images/food-1-xxhdpi.png. So should I write separate API to handle that?
Main file app.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var PORT = 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var foodtruck = require('./model/datafoodtruck');
var db = mongoose.connect('mongodb://127.0.0.1:27017/quflip');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
foodtruck.save(function(err,foodtrucks){
if (err) res.send(err);
});
});
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public/images'));
app.get('/foodtrucklist',foodtrucklist);
app.listen(PORT,function() {
console.log('express listining on port' + PORT);
});
This line
app.use(express.static(__dirname + '/public/images'));
Maps the static content in the /public/images folder to the root of your web application. So the request /public/images/food-1-xxhdpi.png will only work if the full path is .../public/images/public/images/food-1-xxhdpi.png
You should either make your request for /food-1-xxhdpi.png or change the line of code to something like:
app.use('/my-virtual-directory',express.static(__dirname + '/public/images'));
so that requests can be picked up in what ever you choose to make /my-virtual-directory
So... Your file in this case becomes /my-virtual-directory/food-1-xxhdpi.png
Obviously, you can still do this to make it map externally to the same way you have it internally with:
app.use('/public/images', express.static(__dirname + '/public/images'));
Here is more info on the static middleware for express: https://expressjs.com/en/starter/static-files.html
Try:
Backend:
var path = require('path');
var app = express();
var express = require('express');
app.use(express.static(path.join(__dirname, 'public')));
Frontend:
<img src="/images/food-1-xxhdpi.png" alt="">
You can try back-end look like this.
app.use(express.static(__dirname + '/public'));
Then front end use this extract location like
<img src="images/your image name" alt="" />
I am currently working on project and next snippet of code working fine for me:
app.use(express.static('public'));
and when I try to reach this in .hbs it is easy as:
<img src='/images/image.jpg' alt='...' />
Just type following code in your app.js file
app.use('/static/category/', express.static(__dirname+'/public/assets/category_pic/'));
now i will access image by using following code
<img src="/static/category/myimage.jpg" width="50" height="50">
here my actual path is /public/assets/category_pic/ but i convert it /static/category/ using above line of code
now i able to access image file using this url http://localhost:3000/static/category/myimage.jpg
Related
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I'm having some trouble with routing and serving static files.
My directory structure is like this:
app/
--app.js
—-public/
—-js/
—-main.js
—-views/
—-pages/
—-index.jade
This is how I've set up my server:
app.js
var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
var publicPath = path.join(__dirname,'..','public');
var port = process.env.PORT || 3000
var app = express()
app.set('views', './views/pages')
app.set('view engine', 'jade')
app.use('/public', serveStatic(publicPath));
app.listen(port)
console.log("port is " + port)
app.get('/', function(req, res) {
res.render('index', {
title: 'index',
})
})
index.jade
doctype
html
head
meta(charset="utf-8")
title index
script(src="/public/js/main.js”)
body
h1=title
But this is what happens when I visit the index:
GET http://localhost:3000/public/js/main.js 404 (Not Found)
How do I set up the "serve-static" part to work?
Thanks!
you are passing the wrong parameter to it.
correct example for serving static files from different directory would be
This example shows a simple way to search through multiple directories. Files are look for in public-optimized/ first, then public/ second as a fallback.
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
app.use(serveStatic(__dirname + '/public-optimized'))
app.use(serveStatic(__dirname + '/public'))
app.listen(3000)
check out the docs for more options https://github.com/expressjs/serve-static
I think you need to remove public from the path.
script(src="/js/main.js”)
You're telling the server static resources are served from the public folder.
Can we send data to another client ejs i's, in another server?
I tried to do:
res.render('/visi-web/home/www/elasticsearch/views/index.ejs', {result:result});
And that's not working.
var elasticsearch = require('elasticsearch');
var express = require('express');
var app = express();
var http = require("http");
var server = http.createServer(app);
app.get('/', function(req, res){
...
res.render('/visi1-sih-web/home/www/elasticsearch/views/index.ejs', {result:result});
});
}
});
server.listen(3333);
Well,you doing it wrong way.
After looking your code,When you hit '/',it load index.ejs .There is no need to give detail path.
Use following syntax.
app.render('index', { result: 'result });
When you set your template engine to ejs or something else, there is no need to give extension.
Also ,Please check your view path is defined or not containing index.ejs.
Just give relative path for index.ejs.
means if you say
app.use(express.static(__dirname + '/public'));
and within publlic folder there is view folder,then you should written in this way.
app.render('view/index', { result: 'result }).
No need to give public folder name in path.
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