Nodejs public folder always fails silently - javascript

I'm trying to include an icon as part of my website, currently my code looks like the following:
app.js
const http = require('http');
const fs = require('fs');
const express = require('express')
const path = require('path')
const hostname = '127.0.0.1';
const port = 3000;
const html_file = "./index.html";
var app = express()
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static('public'));
console.log(path.join(__dirname, 'public'));
fs.readFile(html_file, function (err, html) {
if (err) {
throw err;
}
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(html);
res.end();
}).listen(port);
console.log(`Listening on http://${hostname}:${port}`)
});
While my html file looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<body>
<p>test text</p>
</body>
</html>
However, the icon is never loaded properly.
I can see that the request returns in the network inspection tab, and there are no errors from nodejs in the console, but no matter what it fails.
I've tried switching between adding and not including the /public/ in the link line too, as well as moving the HTML file to the public folder itself.
Any ideas?

You're starting a vanilla HTTP server that only serves your index.html file and nothing else.
I'd suggest moving index.html into the public folder and using app.listen() to start your Express app instead.
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
app.use(express.static(path.join(__dirname, "public")));
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
I highly recommend working through the Express Getting Started guide.
You should also use an absolute path to your icon in the HTML
<link rel="icon" type="image/x-icon" href="/favicon.ico">

Related

Dynamically change the meta tags of a React Js application using Express Backend

I have been doing some research on dynamically changing the meta tags for my react Js application. I have tried so many solutions such as Helmet but I have not succeeded.
I will be glad if someone can give me a clear algorithm on this task. I have two backends one is in Express and another one in PHP. I created the Express backend purposely for this task yet I have not succeeded in getting the meta tags change when I share my link to other platforms like Facebook.
My current implementation.
Frontend:
My Index.html inside public has
<title>$OG_TITLE</title>
<meta name="description" content="$OG_DESCRIPTION" />
<meta property="og:title" content="$OG_TITLE" />
<meta property="og:description" content="$OG_DESCRIPTION" />
<meta property="og:image" content="$OG_IMAGE" />
Express Backend
const express = require('express');
const cors = require("cors");
const path = require('path');
const fs = require('fs');
const app = express();
app.use(cors());
const port = process.env.PORT || 2800;
app.use('/api/dynamicmeta', (req, response)=>{
const filePath = path.resolve(__dirname, './build', 'index.html')
fs.readFile(filePath, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
data = data.replace(/\$OG_TITLE/g, 'Contact Page');
data = data.replace(/\$OG_DESCRIPTION/g, "Contact page description");
result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
response.send(data);
});
});
app.use(express.static(path.resolve(__dirname, './build')));
app.get('*', function(request, response) {
const filePath = path.resolve(__dirname, './build', 'index.html');
response.sendFile(filePath);
});
app.listen(port, () => console.log(`listening on port ${port}!..`));
module.exports = {
app
}
At this point, I am confused on how to continue because the title of my build doesn't change.

How to refer a css file from index.html in React

I have a folder called assets which have a styles.css and then I have index.html which I would want to reference styles.css but for some reason it can't.
My current solution is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My App</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>
And I have the node server running like this:
var webpack = require("webpack");
var config = require("./webpack.config.js");
var http = require('http');
var express = require('express');
var app = express();
var proxy = require('http-proxy-middleware');
var path = require('path');
const compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: "/"
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use('/auth', proxy('http://localhost:8081', {changeOrigin: true}));
app.use('/api', proxy('http://localhost:8081', {changeOrigin: true}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
/**
* Anything in public can be accessed statically without
* this express router getting involved
*/
app.use(express.static(path.join(__dirname, 'assets'), {
dotfiles: 'ignore',
index: false
}));
var server = http.createServer(app);
server.listen(3000, function() {
console.log("express listening at localhost:3000");
});
This is not working for me it cannot find the css file, how can I make it so I can reference the css file from index.html. Also I have index.js on my src folder which is used as an entrance file for running the whole React App.
Add the route for styles.css before app.get("*",...)
app.get("/styles.css", function(req, res) {
res.sendFile(__dirname + '/styles.css');
});

How to link an existing Angular 2 app to Nodejs Server?

I have an Angular 2 app with this structure :
Structure of my Angular app
Then in server side :
Structure of server app
I see that there is 2 module dependencies folders, but I don't know which one I sould keep.
Here is my index.js file :
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
//const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'client/portfolio')));
// Set our api routes
//app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
When I start server I get this message :
Loading AppComponent content here ...
But it stops here and doesn't render the Angular application.
index.html file :
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link href="node_modules/#angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/hammerjs/hammer.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
Here's a good example of integrating AngularJS with NodeJS [open tutorial]
The trick is in this block
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});

Cannot load html image using localhost node.js/express.js server

I'm using the following node.js/express.js server,
index.js:
const express = require('express');
const path = require('path');
const app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8000, function () {
console.log('Listening on port: 8000!');
});
and the following html file,
index.html:
<!doctype html>
<html>
<head>
<title>Will Alley</title>
</head>
<body>
<style type="text/css">
img {
width: 100%;
height: 100%;
}
</style>
<h2 id="myName">Will Alley</h2>
<img src="./DSC_1546_700_464.jpg" alt="an image.">
</body>
</html>
all my files (index.js, index.html, DSC_1546_700_464.jpg) are in the same directory.
when I start my server and navigate to "localhost:8000" all that is displayed is the heading, and the images alt text.
Any help is greatly appreciated.
You have only one route in express, the one for '/'.
Below are two additions, one that answers your specific question by adding app.use(express.static(__dirname)) which is dangerous. The safer way is to use something like app.use('/images',express.static(__dirname+'/images')) to serve just certain subdirectories where you put servable stuff.
const express = require('express');
const path = require('path');
const app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
// Static route for files in the current directory...
// Note that this serves all files relative to the given
// path, even ones you probably don't want.
app.use(express.static(__dirname));
// Note: you should really put these files in a subdirectory
// And use static like this:
app.use('/images', express.static(__dirname +'/images'));
app.listen(8000, function () {
console.log('Listening on port: 8000!');
});

Express.js not finding stylesheet

I'm working on an app using the MEAN stack, and I'm having trouble getting my main index page to pick up my stylesheet. Running node server works fine, the index.html page is rendering, and there are no console errors. Hitting http://localhost:3000/public/css/app.css returns the CSS as expected. So the file is there and accessible, but the styles aren't being applied to the index page.
Any idea what's going on?
./server.js
var config = require('./server/config/environment');
var express = require('./server/config/express');
var app = express();
app.listen(config.port, function() {
console.log('Server is listening on port %d', config.port);
});
exports = module.exports = app;
./server/config/express.js
var express = require('express');
var path = require('path');
module.exports = function() {
var app = express();
app.set('view engine', 'ejs');
require('../server.routes.js')(app);
app.use("/public/css", express.static(path.resolve('public/css')));
app.get('/public/css/app.css', function(request, response) {
response.sendFile(path.resolve('public/css/app.css'));
});
return app;
};
./server/server.routes.js
module.exports = function(app) {
app.get('/', require('./server.controller').render);
};
./server/server.controller.js
module.exports.render = function(request, response) {
response.render('index');
};
./views/index.ejs
<head>
<base href="/">
<link rel="stylesheet" src="/public/css/app.css">
</head>
./public/css/app.css
body {
margin: 70px 20px 20px 20px;
}
Try this
./views/index.ejs
<head>
<base href="/">
<link rel="stylesheet" href="/css/app.css">
</head>
./server/config/express.js
var express = require('express');
var path = require('path');
module.exports = function() {
var app = express();
app.set('view engine', 'ejs');
require('../server.routes.js')(app);
app.use(express.static(path.resolve(__dirname, 'public')));
return app;
};
When you use express.static() you are registering that as a public folder, meaning the client doesn't need to actually know what the name of the folder is. Essentially what you were doing was calling
<head>
<base href="/">
<link rel="stylesheet" href="/public/css/public/css/app.css">
</head>
Usually people register a base folder and then put the css in the css/ subfolder and the js in the js/ subfolder
EDIT: #HydraHorn realized on his own that he was using <link src="..."> instead of <link href="...">. That said it still would not have worked without the changes to express.static(). I have made the changes above to not confuse future visitors

Categories