Node express app.get("/.." parent directory not working - node.js

./core/server.js
./core/index.html
./core/styles.css
./bin/init-transpiled.js
How can I host index.html at localhost:8000 (not /core) where index.html still has access to relative paths ../bin/init-transpiled and ./styles.css?

You can host your index.html file like this.
app.get('/', function(req, res) {
res.sendFile(path.resolve(__dirname + "/index.html"));
});
And you need to set bin folder as static folder in your server configuration to access bin folder files from client side.
app.use(express.static(path.resolve(__dirname + '/../bin')));
Then in index.html you can access your file like this.
<script src="../bin/init-transpiled.js">
Note that if index uses ./styles.css for example, you would need to use ../core/styles.css

app.use('/', express.static(__dirname));
app.use('/', express.static(__dirname + '/../'));
app.get('/', function (req, res) {
res.sendFile(__dirname + "/index.html");
});
When '/' is used,
statically host this dir (for accessing local ./styles.css for example)
statically host the parent dir (otherwise you can't traverse through ../bin/)
send index.html as a response.
Note: '/' is not required, the default is '/' and you can just write your middleware handler function as the first param
See Express Docs - static files

Related

Setting up two different static directories (angular apps (dist) in node.js Express framework? is not working?

I have two angular apps and single node app both angular apps consuming api's from node app. I want to setting up these two clients apps from nodeJs. i wrote the following code but its not working as expected?
I tried this first.
app.use("/", express.static(__dirname + '/admin-dist'));
app.use("/customer", express.static(__dirname + '/customer-dist'));
but did'nt work from me then I tried this.
then I tried this.
app.use(express.static(__dirname + '/admin-dist'));
app.use(express.static(__dirname + '/customer-dist'));
app.all('/customer', (req, res) => {
res.status(200).sendFile(__dirname + '/customer-dist/index.html');
});
app.all('*', (req, res) => {
res.status(200).sendFile(__dirname + '/admin-dist/index.html');
});
If I am doing something wrong? let me know. Thanks!
URL is /customer and the file is __dirname + "/customer-dist/index.html OR URL is / and the file is __dirname + "/admin-dist/index.html
For that first situation, you would use this:
app.use("/customer", express.static(path.join(__dirname, "customer-dist")));
With that statement, you will get the following:
/customer => __dirname/customer-dist/index.html
/customer/foo.html => __dirname/customer-dist/foo.html
/customer/admin/test.html => __dirname/customer-dist/admin/test.html
For the second, you would use this:
app.use(express.static(path.join(__dirname, "admin-dist")));
And, that will match up these requests with these files:
/ => __dirname/admin-dist/index.html
/foo.html => __dirname/admin-dist/foo.html
/admin/test.html => __dirname/admin-dist/admin/test.html
You should make sure the two statements are in the order shown here so the more specific statement /customer one is first and the less specific one doesn't have any chance of stealing requests from the more specific one.
If these aren't working for you, then something else about your configuration or your problem statement is wrong.
In NodeJS the order of youe middleware matters. Route / will match both / && /customers hence why they're going to the same application. Switching the order should correct the issue.
app.use("/customer", express.static(__dirname + '/customer-dist'));
app.use("/", express.static(__dirname + '/admin-dist'));

return the path of an image that is hosted on my server to show it on the fron-end

currently on my server I have under the path theses images:
/opt/myproject/assets/5259521.jpg
/opt/myproject/assets/5259522.jpg
/opt/myproject/assets/5259523.jpg
I am using nodejs to create my web services. I want to know what is the way to return the path of my images so that the front-end can show them in an img tag.
my restAPI can be accessed by a path:
http://3.89.xx.xx/getImages
Here I would need to return the image paths so that I can display them in my web application.
app.use(cors());
app.options('*', cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
// Configuración global de rutas
app.use(require('./routes/index'));
const distDirectory = path.join(__dirname, '/public');
app.get('*', function (req, res, next) {
const file_path = path.join(distDirectory, req.url.split('?').shift());
if (fs.existsSync(file_path)) next();
else res.sendFile(path.join(distDirectory, 'index.html'));
});
app.use(express.static(distDirectory));
thanks
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
You need to put all you images in public folder or add the folder name of you choice and then pass the static folder in the express.static middleware.
The name of the folder Public is just a convention, you can set name of folder to anything.
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'))
And access it like :
http://localhost:3000/assets/5259521.jpg
I am assuming that you the images are under public/assets folder.
To use the static files in Node js
There is a path called 'public' which holds all the files CSS, Bootstrap, Images etc.
add this line to the code
app.use(express.static("public")
if the structure of public folder is
-public
-css
-picture
-images
then you have use images for frontend
<img src = "picture/a.png">
<img src = "image/b.png">
<img src = "image/c.png">
you can have many folders in public folder

node.js: serve static web, match request url //*/web/ to file system /web/

I use node.js in a simple way to serve a static web.
...
app.use(express.static('./build'));
http.createServer(app).listen(port, ipaddress);
...
This serves the files 1:1 (with index.html as default resource), e.g.
//server/a.html -> ./build/a.html
//server/bbb/x.html -> ./build/bbb/x.html
//server/ccc/ -> ./build/index.html
But now, I need to be able to remove 'one level' of the request url, but it shall serve still the same web, e.g.
//server/aaaa/a.html -> ./build/a.html
//server/bbbb/a.html -> ./build/a.html
//server/xxxx/bbb/x.html -> ./build/bbb/x.html
//server/yyy/ccc/ -> ./build/ccc/index.html
So I need a wildcard matching in the request url. I tried this:
app.use('/\*', express.static('./build'));
http.createServer(app).listen(port, ipaddress);
But with no luck. No more page is accessible. What is wrong?
[Edited to show that the server should serve index.html as default resource]
Depending on your application, you might put express.static() on separate Router instances that are mounted on your app. For example:
var routerA = new express.Router();
// You could also reuse the same static file handler since they
// are all using the same root path
routerA.use(express.static('./build'));
// and other `routerA` route handlers ...
var routerB = new express.Router();
routerB.use(express.static('./build'));
// and other `routerB` route handlers ...
// etc.
However if you don't have your application broken up like this already, you could also specify multiple routes like:
app.use(['aaaa', 'bbbb', 'xxxx'], express.static('./build'));
Or if nothing else, you could just use a custom middleware, calling the static file handler manually (although this is kind of a hack, as it was what separate, mounted Routers were designed to help solve):
var staticHandler = express.static('./build');
app.use(function(req, res, next) {
var m = /^\/[^/]+(\/.+)$/.exec(req.url);
if (m) {
// Temporarily override the `req.url` so that the path
// concatenation will happen correctly
var oldUrl = req.url;
req.url = m[1];
staticHandler(req, res, function(err) {
// Reverting the to the original `req.url` allows
// route handlers to match the request if a file
// was not found
req.url = oldUrl;
next(err);
});
} else
next();
});
app.get('/aaa/foo', function(req, res) {
res.end('hello from /aaa/foo!');
});
My final solution is:
// serve all files from ./web directory regardless of first element in url
app.get('/:leveltoremove/*', function(req, res) {
var path = req.params[0] ? req.params[0] : 'index.html';
res.sendfile(path, {root: './web'});
});
http.createServer(app).listen(port, ipaddress);

Exclude sub directory from static files in express

Is there any way to exclude sub directory from express static middleware in express 4.8.5.
For example if I have :
app.use(express.static(__dirname + 'public'));
And my public directory is like this :
- public
- css
- images
- scripts
- index.html
- exclude_me
- scripts
- views
- index.html
So I need to exclude last sub directory and when user does :
GET /exclude_me
It should call my route rather than returning directory automatically.
I can't just remove it from public dir because it depends on stuff inside it because public directory is angular application and exclude_me is another angular application that fetches scripts from /exclude_me/scripts AND from /public/scripts.
I know it is little confusing but it is how it is and I cannot just remove it from public dir because it won't see public/scripts any more which are needed and I cannot leave it because I cannot authorize it then (all authorization is in public/scripts)
If there is some smarter way to do this, feel free to let me know :)
You can add your own middleware. Here's what I did to exclude some folders:
app.use('/public', (req, res, next) => {
if (env !== 'development') {
var result = req.url.match(/^\/js\/(maps|src)\/.+\.js$/)
if (result) {
return res.status(403).end('403 Forbidden')
}
}
next()
})
app.use('/public', express.static(path.join(__dirname, '/public')))
It's possible by adding regular expressions to the first optional param of use method.
According with Express 4.x API path documentation.
Example, I don't want to give access to my secure folder inside public folder:
var express = require('express');
var app = express();
app.use([/^\/public\/secure($|\/)/, '/public'], express.static(__dirname + '/public'));
This will allow you to access all files but not the ones in the secure folder.
You can use it also to restrict a file extension, example files that ends with .js.map:
app.use([/(.*)\.js\.map$/, '/public'], express.static(__dirname + '/public'));
And you also can add multiple rules, like this example where secure folder and files that end with .js.map are ignored from the static folder:
app.use([/^\/public\/secure($|\/)/, /(.*)\.js\.map$/, '/public'], express.static(__dirname + '/public'));
I had a similar problem, which may be the answer you were seeking. Given the following directory:
public
css/
images/
secure/
index.html
The Express Middleware stack I wanted was this:
1. Static files (except the `secure/` directory)
2. Logging
3. Authentication
4. `secure/` static files
Here's how I solved it:
var express = require('express');
var path = require('path');
var app = express();
// path.join here makes it work cross platform with Windows / Linux / etc
var statics = express.static(path.join(__dirname, 'public'));
function secureStatic(secure) {
return function (req, res, next) {
if (/^\/secure/.test(req.path) === !!secure) return statics(req, res, next);
return next();
};
}
// add public files
app.use(secureStatic());
app.use(logging());
app.use(authentication());
// add secured files
app.use(secureStatic(true));
This will only serve public files when unauthenticated, and only serve secure files after authentication.
Most solutions above are to use a middleware.
However, there is a just easier way to solve this.
Don't serve static assests directly with the dir public rather than serve dir just what you want to serve with a virtual path prefix .
You can serve like below
var express = require('express');
var app = express();
app.use('/public', __dirname + 'css');
app.use('/public', __dirname + 'images');
...

Serve out 'static' route with express with redirect and middleware

I am serving out a static url with express 4.0:
app.use('/static-route', express.static('./static'));
And that works great.
However I would like to redirect my users to a url with a query parameter if they hit that route.
ie /static-route -> /static-route?someQueryParam=hello
I would also like to include middleware for that static request. As a concrete example I am using passport and would like to make sure the user is logged in to access that static content.
app.use (and app.get etc . . .) doesn't take two parameters, the first parameter is the route (optional for use), then the rest are all middleware.
app.use('/static-route', function (req, res, next) {
// validation
// redirect
// etc . . .
next();
}, express.static('./static'));
Use global wilcard route[ app.use('/') ] for static content and
Use specific routes [ app.get(/myroute), app.post('/anotherroute')] for dynamic processing using custom logic
//Serves resources from public folder
app.use('/',express.static(__dirname + '/public'));
//Verify the complete directory path - especially slashes
console.log('Static directory '+__dirname + '/public');
app.get('/list', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>'); });

Resources