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

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!');
});

Related

Nodejs public folder always fails silently

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">

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');
});

Express static files URL changes based on route

I have create-react-app thats using react-router-dom. I'm also using express server-side-rendering for SEO. Below is my simple express config. When I got to the '/' route or any of the first-level routes ("/contact", "/blog", etc), it works as intended. The static files come in as:
"http://localhost:8080/static/css/main.ec91a01d.css".
But when I navigate to any multi-level routes ("/blog/blog-post-1"), it adds the first route to the static files URl ex:
http://localhost:8080/blog/static/js/main.d9a1d852.js
What am I doing wrong? Also, the folder structure is that of a regular Create-react-app. Im serving my index.html from the build folder and my styles/js from build/static.
Project
----build
----public
...etc
And my server.js
const express = require('express');
const path = require('path');
const ssr = require('./ssr.mjs');
const app = express();
const crawler = async (req, res) => {
const isBot = req.get('User-Agent').indexOf('Googlebot') > -1 ||
req.get('User-Agent').indexOf('googlebot') > -1;
if (isBot) {
const { html } = await ssr(`http://www.example.com${req.path}`);
return res.status(200).send(html);
}
res.sendFile(path.join(__dirname + '/build/index.html'));
};
app.use(express.static('build'));
app.get('/', crawler);
app.get('/process', crawler);
app.get('/work', crawler);
app.get('/contact', crawler);
app.get('/blog', crawler);
app.get('/blog/create-post', crawler);
app.get('/blog/:id', crawler);
app.get('/services', crawler);
app.get('/services/:id', crawler);
app.get('/payments', crawler);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log('Server started. Press Ctrl+C to quit'));
You seem to be fetching your ressources with relative paths in your index.html, e.g.
<script src="./static/js/main.d9a1d852.js"></script>
What you want are absolute paths:
<script src="/static/js/main.d9a1d852.js"></script>
Notice the missing . at the beginning of the path.

Navigation using express and EJS

Having a issue figuring out how to navigate between EJS pages effectively:
File directory:
I want to go from my index.ejs page to the about.ejs page. This is the code for my index.ejs page which is currently not navigating properly:
index.ejs:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1> This is a link to about page</h1>
</body>
</html>
app.js server:
const express = require("express");
const path = require('path');
const app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")
app.get("/", (req, res) => {
res.render("index")
});
app.use(express.static('public'));
app.listen(3000);
What could I enter in the href to properly reference the dynamic about.ejs file?
I already know that I can reference static files from my public folder but I want to refernce the dynamic ejs folder. If not possible any solution which provides the same functionality will also do.
You should render about.ejs template to use it on the client. To do that, you need to create a new route:
app.get("/about", (req, res) => {
res.render("about");
});
To open it use /about path.
Your link should point to /about.
Then you have to options. 1) have a function in your server to serve that page. 2) serve your pages dynamically.
1.
app.get("/about", (req, res) => {
res.render("about")
});
2.
app.get("/:page", (req, res) => {
res.render(req.params.page);
});
You need to create a route for your about page
app.get("/about", (req, res) => {
res.render("about")
});
And remove the extension from the hyperlink. The hyperlink should be :
About
Notice the correction in your index.ejs at line 7
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1><a href='/about'> About</a></h1> //there's no point including the ".ejs" extension at the end of the "about"
</body>
</html>
In your app.js server, also notice the addition of the (about route).
const express = require("express");
const path = require('path');
const app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")
app.get("/", (req, res) => {
res.render("index")
});
app.get('/about', (req, res)=>{ //here you can include a new "about" route that should take you to the "about" page
res.render('about')
});
app.use(express.static('public'));
app.listen(3000);

Dont find socket.io

Files
chat
node_modules
web
public
css
estilo.css
img
tiempo.jpg
js
script.js
view
vista.html
app.js
package.json
JSON
{
"name":"chat",
"version":"0.0.1",
"privte":"true",
"dependencies":{
"socket.io":"1.4.8",
"express": "4.14.0"
}
}
In the File vista.html I can't open or load the soket.io, but I can load the files: pictures, css, js - don't have a problem with that. The problem is to try to load soket.io
NODE.js File, app.js
var express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
nicknames=[],
users={};
app.listen(3000, function () {
console.log('SERVIDOR LISTO');
});
app.use(express.static(__dirname + '/web/public'));
app.get("/",function(req, res){
res.sendFile( __dirname+'/web/public/view/index.html');
});
io.sockets.on("connection", function(socket){
.......
.......
}
and my html file is
<html>
<head>
<title></title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<img src="http://localhost:3000/img/tiempo.jpg"
alt="Smiley face" height="30%" width="30%">
</body>
</html>
I found the solution to my problem. I had to reorder the code, what starts first and finish with the last.
var express = require('express'),
app = express(),
io = require('socket.io'),
nicknames=[],
users={};
var server=app.listen(3000, function () {
console.log('SERVIDOR LISTO');
});
var mysocket = io.listen(server);
app.use(express.static(__dirname + '/web/public'));
app.get("/",function(req, res){
res.sendFile( __dirname+'/web/public/view/index.html');
});

Categories