I am using the below code to serve statics files(js, images, css):
app.use(express.static(path.join(__dirname, 'public')));
But now the images have been moved to some different location in the project i.e. outside the public directory (lets say. images).
So how do I differentiate between images and js,css files and serve them from different locations?
EDIT
I guess I have to read the request headers and then decide where to route the request. But looks a little dirty to me.
Try with two separate endpoints:
import express from "express";
import {join} from 'path';
const app = express();
const publicPath = express.static(join(__dirname, '../public/'));
const publicImages = express.static(join(__dirname, '../images/'));
app.use('/public', publicPath);
app.use('/images', publicImages);
app.listen(3400, function() {
console.log("Express server listening on port 3400");
});
Then you use it like this: http://localhost:3400/images/ and http://localhost:3400/public/
In that case you just need to add one more static file configuration
app.use(express.static(path.join(__dirname, 'images')));
And it will be served as
http://example.com/files-from-images-folder
Related
I am trying to serve static files with express.static but on files that are 1MB - 5MB it seems to take for ages to load. As you can see I am already adding the static middleware as first one.
const app = express();
app.use("/", express.static("./Client/Static"));
const httpServer = http.createServer(app);
httpServer.listen(Config["http-port"], () => console.log("STARTED HTTP SERVER ON " + Config["http-port"]));
app.set("views", path.join(__dirname, "Client/Views"));
app.engine("html", ejs.renderFile);
app.set("view engine", "html");
app.use(cookieParser());
app.use(bbBodyParser({
"limit": "6mb"
}));
Result, when reloading without cache (The file is so big because its the entire Font Awesome Library):
there's an issue for this situation, i guess you can find the solution here
https://github.com/expressjs/express/issues/321
but in a production enviroment it's better use cdn like s3 or other you may like.
I'm fairly new at web development and I've been having an issue with requiring certain node modules in my Express application. I need to access certain code, but I'm having difficulty with the the intricacies of Node, and can't for the life of me access node_modules where I need to.
What I'm attempting to do is utilize the Cloudinary video-player from the node_modules that I've installed. I've included path links in the index.html file which is served from htmlRoutes.js, and I've explicitly directed express to statically load these files within the document, but the application does not recognize these paths as valid. I've tried requiring these modules in separate JS files served up from the public folder, but that's also invalid. From what I understand it might be my own confusion of client-side vs server-side programming, but I don't know how to resolve this, nor what resources I should be reading in order to do so.
Any help would be appreciated. Here's what my server looks like:
const express = require("express");
const path = require('path');
const bodyParser = require('body-parser');
const baguetteBox = require('baguettebox.js');
const cloudinary = require('cloudinary');
const axios = require("axios");
const app = express();
// Define a port to listen for incoming requests
// Sets an initial port. We"ll use this later in our listener
const PORT = process.env.PORT || 8181;
app.use(express.static('public'));
//static routes that attempts to fetch scripts from node_modules without revealing inner directory structure
app.use(express.static(__dirname + '/node_modules/lodash'));
app.use(express.static(__dirname + '/node_modules/cloudinary'));
app.use(express.static(__dirname + '/node_modules/cloudinary-core'));
app.use(express.static(__dirname + '/node_modules/cloudinary-video-player'));
// Sets up the Express app to handle data parsing
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//routes
require("./routes/htmlRoutes.js")(app);
// require("./routes/apiRoutes.js")(app);
//configure cloudinary api calls
// cloudinary.config({
// cloud_name: 'name',
// api_key: 'key',
// api_secret: 'secret',
// secure: true
// })
// Start our server so that it can begin listening to client requests.
app.listen(PORT, function() {
// Log (server-side) when our server has started
console.log("App listening on: http://localhost:" + PORT);
});
I have never seen node_modules packages served as static files directly, having said that, I will be agnostic with that working.
An alternative way to deal with this issue is to use a bundler such as Webpack and serve it with Express.js
The reason for this is that even being JavaScript, Webpack will compile the code into something interpretable by the browser, something that in many cases you do not find in a package of Node.js
If you need for example lodash, you dont have to access to node_modules/lodash. Just import lodash by declaring:
const lodash = require('lodash');
And you can now use lodash in the file you declaring lodash.
When using React-Router, you only serve up the original index.html with Node because the client handles the rest. I understand how to route between different pages once the user is at the home page. However, let's say the user types in the URL '/about'. Node will serve up the index.html, but how do you tell React-Router to then immediately take the user to the about page? Thank you.
If you have your BUILT create-react-app project sitting inside you node/public folder. you need to let express know that the index.html file will be handling the routes. see super simple server example below. this will use react routers setup properly.
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'public/index.html')));
app.listen(3000);
This is the code that I see everywhere for a simple static web server using node.js and express:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
My question is how does express know when the request is for a static page vs. a dynamic page? For example, why would /index.html be served from the public folder and not from dynamic templates?
Thanks.
You can think of the routes you define as a chain of checks on the path defined in the URL. Express iterates one by one through each check looking for a match; once it finds one, it executes that callback.
In this case, express.static is defining a bunch of path checks for each file in the public directory. If you app.use(express.static(__dirname + '/public')); before your app.get('/index.html', function(req, res) { ... code, and there is an index.html file in there, it will use the static file over the dynamic one.
That's basically it.
I am using Express v3.0.0rc1 with Node v0.8.1 and I am trying to create a webserver that works off of a modular system for displaying routes and views.
Is there a way to display stylesheets and client-side javascript files from within the ./modules/foo/ directory instead of ./public when display requests from within the foo module routes?
My approach would be to set up an additional static middleware layer. This has the limitation that the static files used by your modules must have different names since any name conflicts will result in only the resource from ./public being served. According to this SO Setting up two different static directories in node.js Express framework, this may be the best you can do.
var express = require('express');
var http = require('http');
var app = express(); // Express 3+
var server = http.createServer(app);
app.configure(function(){
app.use(express.bodyParser()); // Parses incoming request date.
app.use(app.router); // Mount application routes
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/module/foo'));
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
});