I'm trying render the index file with Express Node.js successfully, but if I'm using namespaces with parameter, without parameter render twig file and included own scripts, if I use try with parameter, render ok bu problem with script files path so script files in head in html cannot including while path not correct
for example, without parameter, in html file style.css look like
<link rel="stylesheet" href="style.css"> path http://127.0.0.1:3000/style.css
with parameter, in html file style.css look like <link rel="stylesheet" href="style.css"> path http://127.0.0.1:3000/mynamespace/style.css <--- and this not found!
say browser path not found!
Server.js
const port = 3000;
const express = require('express');
const app = express();
const http = require('http');
const socketIO = require('socket.io');
const server = http.Server(app);
server.listen(this.port, () => {
console.log(`Server running on: http://127.0.0.1:${port}`);
});
const io = socketIO(server);
app.set('view engine', 'twig');
app.set('views', "views");
app.use(express.static('public'));
app.use(express.static('scripts'));
app.use(express.static("styles"));
/// Routing
/**
* This work fine
* Render client.twig
* Including Scripts in head
*/
app.get('/mynamespace', function (req, res, next) {
res.render("client");
});
/**
* This work with error
* Render client.twig
* don't Including Scripts in head
*
*/
app.get('/mynamespace/:id', function (req, res, next) {
res.render("client");
});
io.of("/mynamespace").on('connection',(socket)=>{
socket.on('online_users', (data) => {
console.log(`Online Users ${data}`);
});
});
client.js
let url = `http://127.0.0.1:3000/mynamespace`;
console.log("Url", url);
this.socket = io(url);
this.socket.on("connect", ()=>{
try{
this.socket.emit('welcome', {
message:"Welcome guest"
});
} catch (e) {
alert(e.message);
}
});
client.twig
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
<title>RestoCommend</title>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" href="style.css"
</head>
<body>
<h3>Client</h3>
<script src="helper.js"></script>
<script src="client.js"></script>
</body>
</html>
From your code it looks like the style.css file is in the same directory as client.twig which is the views directory. But you have told express that the static directories are public, scripts and styles. There is no instruction for express to know where to serve the css from. Try moving the style.css file into styles directory.
Good luck.
Sounds like you want to serve your static files under a relative path. Try the following:
app.use('/mynamespace', express.static('public'))
app.use('/mynamespace', express.static('scripts'))
app.use('/mynamespace', express.static('styles'))
And also
<link rel="stylesheet" href="mynamespace/style.css" />
My hierarchy of files
I Solved my problem, but not good idea
Server.js
app.get('/mynamespace1', function (req, res, next) {
app.use(express.static('public'));
app.use(express.static('scripts'));
app.use(express.static("styles"));
res.render("client1");
});
one parameter based namespace!
app.get('/mynamespace2/:clientId', function (req, res, next) {
app.use(express.static(path.join( __dirname + "/../", 'public')))
app.use(express.static(path.join( __dirname + "/../", 'scripts')))
app.use(express.static(path.join( __dirname + "/../", 'styles')))
res.render("client2");
});
more as one parameter based namespace!
app.get('/mynamespace3/:roomName/:clientId', function (req, res, next) {
app.use(express.static(path.join( __dirname + "/../", 'public')))
app.use(express.static(path.join( __dirname + "/../", 'scripts')))
app.use(express.static(path.join( __dirname + "/../", 'styles')))
res.render("client3");
});
client1.twig
<link rel="stylesheet" href="style.css">
<script src="helper.js"></script>
<script src="client.js"></script>
Everything normal
client2.twig
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" href="../style.css">
<script src="../helper.js"></script>
<script src="../client.js"></script>
with one prameter, script paths defined to parent
client3.twig
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" href="../../style.css">
<script src="../../helper.js"></script>
<script src="../../client.js"></script>
with more prameters, parent folder defined, until number of parameter
My Problem solved, but I don't like it so
Related
My folder structure is :
APP
-public
main.js
-views
index.html
index.js
I am trying to serve the static file to express server but its not working. The code for this in my index.js file is:
const express = require('express'),
app = express();
app.use(express.static(__dirname+'/public'));
I have also tried using path.join syntax
In my index.html file in the views folder , I am using the src tag as 'main.js'
<script type="text/javascript" src="main.js"></script>
I get the error net::ERR_FILE_NOT_FOUND.
I can also see that path src is referring to is wrong.
It is looking for main.js file in views directory instead of looking in public directory.
I have looked at other answers. I understand the syntax theoretically but am not able to find what I am doing wrong
Please point out the issue in my code. Thanks
Here is a working example:
index.js:
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, './views/index.html'));
});
app.listen(port, () => console.log(`server is listening on port ${port}`));
./public/main.js:
window.onload = function() {
console.log('onload');
};
./views/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
This is template
</body>
</html>
I'm following a slightly outdated tutorial on node and express, and my code is identical to the tutorial, but app.use is not serving up the public directory as I wish. When I go to the root localhost:3000 I still see Weather like in the tags on line 19. When I delete it, I don't see anything, including the public directory's index.html file.
Here is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> -->
<title>Document</title>
</head>
<body>
<h1>From a static file.</h1>
</body>
</html>
Here is my app.js script:
/* nodejs script that will create, configure, and start the server.
run script: node src/app.js
keep server running: nodemon src/app.js
*/
const path = require('path');
const express = require('express');
const app = express();
const publicDirectoryPath = path.join(__dirname, '../public'); // abs path to serve
// STACKOVERFLOW - WHY ISN'T THIS SERVING UP PUBLIC DIRECTORY?
app.use(express.static(publicDirectoryPath)); // serve 'public' directory
// create root route
app.get('/', (req, res) => {
res.send('<h1>Weather</h1>');
});
// create a help route
app.get('/help', (req, res) => {
res.send([
{name: 'Barack H. Obama'},
{name: 'George W. Bush'},
{name: 'William J. Clinton'}
]);
});
// create an about route
app.get('/about', (req, res) => {
res.send('<h1>About</h1>');
});
// create a weather route
app.get('/weather', (req, res) => {
res.send({
forecast: 'rain',
location: 'Los Angeles'
});
});
// port 3000 is common development port, starts server
app.listen(3000, () => {
console.log('Server is up on port 3000'); // never displays in browser
});
it should be public instead ..public like this
const publicDirectoryPath = path.join(__dirname, 'public')
As app.js and public share the same parent directory at the same level. So ..public will point out to dir public outside src which is not available.
I'm going crazy over this...
I have this simple NodeJS server running - it serves the ./start.html file fine, but the CSS-file is not loaded.
My folder structure looks like this:
/public/css/styles.css
/interface.js (the Node-file)
/start.html
Node is running this code:
const app = express();
const hostname = '127.0.0.1';
const port = 3000;
let serials;
app.use(express.static('public'));
// Make these folders accessible by our HTML-files
app.use('/css', express.static(__dirname + '/public/css'));
//app.use('/js', express.static(__dirname + '/public/js')); // Not used at the moment
//app.use('/images', express.static(__dirname + '/public/images')); // Not used at the moment
app.get('/start', (req, res) => {
const fs = require('fs');
var content;
// We load the file asynchronously and pass on the content to the screen when loaded.
fs.readFile('./start.html', function read(err, data) {
if (err) {
throw err;
}
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length, 'Expires': new Date().toUTCString()});
res.end(data);
});
});
The start.html file looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>start</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link href="css/styles.css" rel="stylesheet" type="/text/css">
<script type="text/javascript">
$(document).ready(function() {
etc...
When accessed, using localhost:3000/start, it only shows the HTML-code.
When opening localhost:3000/css/styles.css it displays the stylesheet just fine.
The browser console also does not show any CSS-file loaded.
Any suggestions, please?
Simple mistake: the CSS linkage had a "/text/css" instead of "text/css" and not an error in the JS after all. Now it works perfectly.
This Link is explaining difference with app.use and app.get. But not explaining about same route problem. So I want to ask my question.
I made react project with create-react-app and make server inside src folder. I want to show text in the index.html when url is root. So I write codes like this.
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<p>Html test</p>
</body>
</html>
src/server/server.js
import express from 'express';
import path from 'path';
const app = express();
const port = 4000;
app.use('/', express.static(path.join(__dirname, '../../public')));
app.get('/', (req, res) => {
return res.send('<p>Hello index</p>');
});
app.get('/hello', (req, res) => {
return res.send('Hello CodeLab');
});
app.listen(port, () => {
console.log('Express is listening on port', port);
});
package.json
"babel-node": "babel-node src/server/server.js --presets es2015"
I test,
localhost:4000/hello --> Hello CodeLab
localhost:4000/ --> Html test (not Hello index)
I thought app.use is just static file which called every time when same url is called by app.get. Why app.get('/')doesn't show <p>Hello index</p> in this project?
Why app.get('/') doesn't show <p>Hello index</p> in this project?
It depends on the order. Re-write like this:
app.get('/', (req, res) => {
return res.send('<p>Hello index</p>');
});
app.use('/', express.static(path.join(__dirname, '../../public')));
You will get <p>Hello index</p> for sure!
The reason is under the hood, app.use() and app.get() both behave just like middlewares, they are treated equally in the Express app. The appear order decides which one is executed first.
an app is an object initialized on the start of express. app.use is for setting midleware More info
to resolve this problem just remove match for a route:
app.use(express.static(path.join(__dirname, '../../public')));
With '/' in app.use you must use next() method then express will go to next controller.
I use compression-webpack-plugin to make gzip files durring my bundle process, so when bundling is done I have files like this in my dist folder.
bundle.eefaef91f71795847e74.js
bundle.eefaef91f71795847e74.js.gz
vendor.jduu4f4lj71759dj7e74.js
vendor.jduu4f4lj71759dj7e74.js.gz
stylesLocal.b7ac53d721aca93e4e65099cf74dc90f.css
stylesLocal.b7ac53d721aca93e4e65099cf74dc90f.css.gz
Inside server I use express-static-gzip to serve my gzip files. Why isn't this working. My page doesnt even wanna load? If I put Express.static instead of expressStaticGzip it works normally.
import Express from 'express'
import path from 'path'
import conf from './conf'
import appRenderer from './appRenderer'
import webpackUtils from './webpackUtils'
var expressStaticGzip = require('express-static-gzip')
const APP_PORT: number = conf.APP_PORT
const PORT: any = process.env.PORT || APP_PORT
const app: Express = new Express()
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(expressStaticGzip(path.join(__dirname, '../', 'dist')))
/* check with the server before using the cached resource */
app.use((req: Object, res: Object, next: () => void): void => {
res.set('Cache-Control', 'no-cache')
return next()
})
/* Use server side rendering for first load */
app.use(appRenderer)
/* Use CommonChunks and long term caching */
app.use(webpackUtils)
// Routes
app.get('*', (req: Object, res: Object) => {
res.render('index', {app: req.body})
})
app.listen(PORT, () => {
console.log(`
Express server is up on port ${PORT}
Production environment
`)
})
And I refernce them in my index.ejs file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>D</title>
<link rel='stylesheet' type='text/css' href="stylesLocal.b7ac53d721aca93e4e65099cf74dc90f.css">
</head>
<body>
<div id="app"><%- app %></div>
<script src="vendor.jduu4f4lj71759dj7e74.js"></script>
<script src="bundle.eefaef91f71795847e74.js"></script>
</body>
</html>
As explained in the readme of express-static-gzip, the syntax is slightly different from express.static.
Instead of
app.use(expressStaticGzip(path.join(__dirname, '../', 'dist')))
try
app.use('/', expressStaticGzip(path.join(__dirname, '../', 'dist')))