how can I render the css files when i use express.js? - javascript

I am grouping my files like so:
node_modules
structures
{HTML Files}
styles
{CSS Files}
app.js
package-lock.json
package.json
I've already required those:
const express = require('express');
const app = express();
const path = require('path')
what do I do next?

I assume that you're somewhat of a beginner with Node/Express.
I recommend you learn more about how express works before deploying this into an actual app.
Let's get something straight: I believe that you only have a group of HTML files that you want to show to the user under the file names eg. example.com/about.html with the homepage HTML file being called index.html so that express knows what to show where.
This is the simplest way I could think i'd achieve this effect.
const express = require('express');
const app = express();
const path = require('path');
// This is the port where the application is running on
// Uses the server's enviroment variable named PORT if is defined else
// this will use port 5000
// the page can be seen locally at http://localhost:5000/
const PORT = process.env.PORT || 5000;
// This line makes the app created earlier use the middleware that express provides for "rendering" static files
// inside the express.static method we give a path to the static files
// to create that path we use the path.join method provided by the path module we imported earlier
// this method takes in all the paths that need to be joined.
// the __dirname is the directory the application was launced from (you can use process.cwd() to get the root)
// and ofcourse the structures is the folder which contains all your HTML files
app.use(express.static(path.join(__dirname, "structures")));
// Now we do the same thing we did before but we add the middleware for the styles under the "/styles" URI.
app.use("/styles", express.static(path.join(__dirname, "styles")));
// This will start the server at the PORT which we defined earlier.
app.listen(PORT);

Related

Nuxt & Express server not getting api requests in production /dist

I have a Nuxt app running successfully on my local server and all API requests are successfully running from the same server (using the serverMiddleware property in nuxt.config.js). When I run a yarn generate, the path to the API server is lost and no data is loaded. Below are a few screenshots.
Loads data successfully from the API.
Unable to find API
Here is an example of an api call in project_dir api/index.js file
const express = require("express");
const passport = require("passport");
const allRoutes = require("../api/routes/routes");
const guestRoutes = require("../api/routes/guest");
const fileUpload = require("express-fileupload");
const path = require("path");
// Create express instance
const app = express();
// Init body-parser options (inbuilt with express)
app.use(express.json());
app.use(fileUpload());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "../", "dist")));
/**
* -------------- PASSPORT AUTHENTICATION ----------------
*/
// Need to require the entire Passport config module so index.js knows about it
require("./config/passport-jwt");
// Initialize Passport
app.use(passport.initialize());
/**
* -------------- ROUTES ----------------
*/
// Imports all of the routes from ./routes/index.js
app.use(guestRoutes);
app.use(passport.authenticate("jwt", { session: false }), allRoutes);
console.log("express");
console.log(path.join(__dirname, "../", "dist"));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../", "dist", "index.html"));
});
// Export express app
module.exports = app;
I don't know why I'm not able to get data from the API routes which I'm running on the same server.
Here is an in-depth answer on how to run an Express server alongside Nuxt: https://stackoverflow.com/a/72102209/8816585
First thing to know, is that you cannot have a Node.js server with yarn generate because it's using target: 'static' and as you can guess, when something is static, it doesn't need a Node.js server to be served to the end-user (only the html + css + js static files are hosted on a CDN or alike).
This mode is meant to host the code on Netlify, Vercel or alike, with no Node.js server available there.
Why is it working locally? Because you do have a Webpack dev server running (with a Node.js server so) for debugging purposes like HMR etc...
TDLR: this is normal (works as intended so far). More info on the given link above on how to make it work.
After much research and debugging I came up with a new idea.
Instead of running npm run start or yarn start containing script "nuxt start" inside the package.json file. I added a new script with the name "express-start": "cross-env NODE_ENV=production node api/index.js". Which runs the express server and nuxt static files.
I'm currently creating a template to make it easier for those who'll face this challenge.
Link to a boilerplate I created after solving the issue.
ExpressJs & NuxtJs Boilerplate

Express.js just won't serve static files

I am trying desperately to get it working that my express server serves statics files but I just can't get it to work... I already tried multiple attempts at solving it but none of it worked.
So my folder structure is the following:
App
- Web
-- public
--- images
--- css
-- Server.js
The code from my server is the following
const express = require('express');
const app = express();
app.use('/static', express.static('./public'));
const server = app.listen(80, function() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server is running on ${host}:${port}`);
});
It just won't serve the files..
No matter how I change the usage of the public folder. I already tried with path.join and __dirname but none of it worked. I only get the express error Cannot GET /static ...
This can happen when the current working directory is not what you think it is and hence ./public doesn't resolve to the right path. The safer way to do this is to use __dirname, the directory of the current file:
app.use('/static', express.static(path.join(__dirname, 'public')));

Locating files using Node.js and Socket.io

I am having trouble with local includes on the client side using Node.js and Socket.io. This may be to my PHP/Apache mindset I have had for file requests for most of my life.
On my server, I load the page likewise:
var express = require("express");
var app = express();
var path = require("path");
var server = require("http").createServer(app);
var io = require("socket.io")(server);
var mysql = require("mysql");
var port = process.env.PORT;
var ip = process.env.IP;
app.use(express.static(__dirname + "/client"));
//start opening socket connection handlers ...
And my files are organized likewise:
games
libraries
bigInt
threejs
etc...
version_1
client
index.html
index.js
index.css
server.js
database.sql
version_2
version_3
etc...
Depending which version I want to run, I open that version's directory and run its server.js file. The line redirects the client to /client/index.html with the line app.use(express.static(__dirname + "/client")). But now only files that are in the client folder are reachable by <script></script> or <link> tags but not those libraries in the libraries folder that I use across versions.
How do I change my code to be able to access files inside the libraries folder from /version_x/client/index.html while still directing the client to proper html file?
Note: Due to this issue, I have been forced to use only libraries with supported CDNs for the past couple weeks I have been learning Node.js.
Add the following line right after var ip = process.env.IP;:
app.use('/libraries', express.static(path.join(__dirname, '..', 'libraries'));
What this does is adding a new route to your application server. All your files inside your /games/libraries folder are now accessible via /libraries.
How does it work? Your express router uses different middlewares based on the provided paths. This line tells the router, to use the static middleware and serve files from ../libraries when a HTTP Request for anything under /libraries comes in.
You can serve more folders with express.static
//Serve Client Folder
app.use(express.static(__dirname + "/client"));
//Server External Libraries Folder
app.use('/libs', express.static(__dirname + "/../libraries"));
//Ex: <script src="libs/threejs/threejs.js">
//Will load libraries/threejs/threejs.js

create-react-app build service-worker.js and manifest.json not found

I have created an app with create-react-app. I have built it and I have written a simple express app for serving the react built app.
I have some problems with the static files and the files which are in the root folder of express app, (e.g. manifest.json, service-worker.js). Now I get 404 on both these files.
How can I treat this files in express? They must be in the static folder? I have to modify the react app?
I went to see the file generated by the react build, in which the file 'service-worker.js' is imported and the string starts with '/' (that is '/service-worker.js')
(I have not touch the files for the pwa since I created the project)
Here there's my root folder of my express app
I have only added the project.json and the index.js (and obviously the node_modules), the other files are those from the react build.
Here my express app:
const compression = require('compression');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use('/sketches', express.static('sketches'));
app.use('/static', express.static('static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'))
app.listen(process.env.PORT || 3000, () => console.log('server listening!'))
Adding this line of code I get the service-worker.js but I can't get the files in the sketches folder.
app.use('/', express.static(__dirname));
I had a same problem i resolved it by following these steps.
warning: i am new to these technologies and i don't know much about web security. this maybe not the best way of doing it.
i get it work using ejs template engine and express but it should work in your case as well.
1) create-react-app
2) yarn build
3) copy static folder into public
4) copy service-worker.js inside static folder also
5) go inside main Ctrl + f
6) type /service-worker.js in search hit Enter
7) you will see somthing like that var e="/service-worker.js";
8) change into var e="/static/service-worker.js
9) finally open service-worker.js change /index.html to /
precacheConfig=[["/","d6be891ca003070326267be1d2185407"]

Sending whole folder content to client with express

I made an html5 game (using GameMaker), which is constituted of an index.html and a folder "html5game" that contains the dependencies of the game - the javascript code and the resources. The problem is the resources are quite numerous and diverse (sounds, sprites, etc.) and The client needs them all to play.
I am looking for a way to send them all without naming them specifically.
I tried the glob module :
var glob = require( 'glob' );
var files = glob.sync( './html5game/**' ).forEach( function( file ) {
require( path.resolve( file ) );
});
but I can't figure a way to send the files using res.sendFile() once I did that.
I tried
var express = require('express');
var app = express();
[...]
app.get('/aeronavale/jeu', function(req, res){
res.sendFile(__dirname + '/aeronavale/index.html');
res.sendFile(files)
});
[...]
app.listen(3000, function(){
console.log('app started on port 3000, yeah !')
})
but it gives me the error :
TypeError: path argument is required to res.sendFile
If you have an other solution, I a also interested. Thanks for your answers !
You will not be able to send multiple file like that with res.sendFile. The most straightforward thing that you can do here would be this:
Put your index.html file and your html5game directory into some common directory, e.g. called html and put it where you have your Node.js program. An example directory layout would be:
/home/you/yourapp:
- app.js (your node program)
- package.json (your package.json etc)
- html (a new directory)
- index.html (your main html to serve)
- html5game (the directory with other files)
- (other files)
Now, in your Node program you can use something like this:
var path = require('path');
var express = require('express');
var app = express();
var htmlPath = path.join(__dirname, 'html');
app.use(express.static(htmlPath));
var server = app.listen(3000, function () {
var host = 'localhost';
var port = server.address().port;
console.log('listening on http://'+host+':'+port+'/');
});
This will serve all of your files (including index.html) on addresses like:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
Of course you still need to make sure that you refer to your assets in your index.html file correctly, for example with:
<script src="/html5game/xxx.js"></script>
in the case of the example layout above.
The top level directory with your static assets (where you have your index.html) is usually called static, public or html but you can call it whatever you like, as long as you use the correct path in your call to express.static().
If you want to have your game available in some path other than the root path then you can specify it to app.use. For example if you change this:
app.use(express.static(htmlPath));
to this:
app.use('/game', express.static(htmlPath));
Then instead of those URLs:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
those URLs will be available instead:
http://localhost:3000/game/ (your index.html)
http://localhost:3000/game/html5game/xxx.js (your assets)
A lot of questions here are related to serving static files with Express so I made a working example and posted it on GitHub so that people could have a working starting point and go from there:
https://github.com/rsp/node-express-static-example
See also some other answers where I talk about it in more detail:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Loading partials fails on the server JS
Node JS not serving the static image
The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.

Categories