Problem with sending static js files to client browser with express.js - javascript

I want to develop a very basic blog app with express.js and I was trying to create a webpage where I could write a post from the browser and store it into a db after submitting it.
By searching on the internet I came upon the ckeditor package, which would allow me to format my blog post before submitting it to the database. I read the documentation and tried to integrate the package in the html code together with the javascript scripts necessary to load the software.
However, when I load the new_post page in my browser I see that the browser is not loading correctly the ckeditor even though I am serving the javascript script necessary to run it as a static resource through the express.static method.
Here you can find the necessary info to check my issue:
Project Structure:
project structure
app.js
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const PORT = 5000;
const newPostRouter = require(".\\routes\\new_post.js");
app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: false }));
//Homepage
app.get("/", (req, res) => {
res.render("homepage", { title: "My Express App", message: "Hello World!" });
});
//Write a new post
app.use("/new-post", newPostRouter);
//Listener
app.listen(5000, () => {
console.log(`Server listening on port ${PORT}...`);
});
routes/new_post.js
const express = require("express");
const router = express.Router();
const path = require("path");
router.get("/", (req, res) => {
res.render("new_post");
});
router.post("/", (req, res) => {
const title = req.body.title;
const content = req.body.content;
res.redirect("/");
});
module.exports = router;
views\new_post.ejs
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
</head>
<body>
<img src="..\public\dog-img.jpg" alt="derp" />
<h1>Classic editor</h1>
<div id="editor">
<p>This is some sample content.</p>
</div>
<script
src="..\public\js_scripts\new_post.js"
type="application\javascript"
></script>
</body>
</html>
public\js_scripts\new_post.js
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
As you can see I am trying to send the static resources to the client browser by using the express.static method in the app.js file. However when I try to load the page in the browser, this is the result I get:
result 1
The dog-img.jpg, also contained in the public folder, is correctly sent to the client yet the javascript file new_post.js is not.
I've also tried to modify the ejs file by substituting the script tag with
<script>
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
</script>
When I do this the editor correctly loads in my browser:
result 2
Since I am trying to follow the best practices I'd like to keep my js files separated from the html/ejs files and therefore I'd like to call the scripts from an external source and not internally.
Can anybody help me understand what is wrong with my code?

In app.js you need to write
app.use(express.static(path.join(__dirname, 'public')));
code to access all data inside the asset folder.
then you need to simple add or load this inside your .ejs file.
<img src="/images/img1.jpg" alt="" srcset="">
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/javascripts/index.js'></script>
For More Details Please visit this link Serving static files in Express

Related

How to use a function of nodejs to use in a button in html for use joohny five?

I create a server using nodejs with express
server.js
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
//__dirname : It will resolve to your project folder.
});
//----------------------------------------------------------------------
//add the router
app.use(express.static(__dirname + '/View'));
//Store all HTML files in view folder.
app.use(express.static(__dirname + '/Script'));
//Store all JS and CSS in Scripts folder.
app.use('/', router);
app.listen(process.env.port || 3000);
And use html with javascript.
index.html
<html>
<head>
<meta charset="utf-8"/>
</head>
<link rel="stylesheet" href="./index.css">
<script type="text" src="./server.js"></script>
<script src="./index.js"></script>
<body>
<h1>Automatico</h1>
<button onclick="autohabilitar();">Habilitar</button>
<button onclick="autodeshabilitar();">deshabilitar</button>
<br>
<h1>Foco-1</h1>
<button onclick="f1habilitar();" id="f1h">Habilitar</button>
<button onclick="f1deshabilitar();"id="f1d">deshabilitar</button>
</body>
</html>
index.js
document.getElementById("f1h").disabled=true;
document.getElementById("f1d").disabled=true;
}
function autodeshabilitar(){
document.getElementById("f1h").disabled=false;
document.getElementById("f1d").disabled=false;
}
function f1habilitar(){
document.getElementById("f1h").disabled=true;
document.getElementById("f1d").disabled=false;
}
function f1deshabilitar(){
document.getElementById("f1d").disabled=true;
document.getElementById("f1h").disabled=false;
}
I need the function
function apagarf1(){
led1.off();
}
located in server.js for use in onclick of the button...
I tried export the function, import the script in the html, use johnny-five in another script...
I’m not super familiar with Johnny 5. But I do know you can’t access node.js specific stuff from the browser.
Your best bet will be to set up a basic api endpoint in express that you call from your front end code. When that endpoint gets hit you can trigger your nodejs function to turn the led off.
In your server file add this:
app.get('/led-off', (req, res) => {
apagarf1()
return res.send('LED off');
});
On your front end make a fetch() call to that endpoint and that should work.

Why is html page sent by express.js route not connected to a css stylesheet?

So I have server.js file that imports a router
const path = require("path");
const express = require("express");
const app = express();
const PORT = 8080;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(require('./app/routing/htmlRoutes'));
The router looks like this
const path = require("path");
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.sendFile('home.html', { root: path.join(__dirname, '../public') });
});
router.get('/survey', function(req, res) {
res.sendFile('survey.html', { root: path.join(__dirname, '../public') });
});
module.exports = router;
It does work! It renders html pages, however those html pages have css stylesheets hooked up to them and located in the same directory, but they render as blank html sheets (unstyled)...
How do I make them render with css stylesheets taken into account?
When the browser encounters the style reference of the loaded html file, it tries to load the file specified in the src attribute. Now your server script doesn't have a route for that. It will load the css if you add a route for that specific css file. However as Irshad said, the standard way to do this is to add a route for all the static files.
app.use(express.static("public"))
Right now, you are only sending home.html everytim the root is requested.
Change your code to read the requested file from the req and serve that file whatever it may be.
Why not set the middleware to serve static files (css, html) from public folder app.use(express.static("public"))
See the working example

Image not found in webpage served with node.js and express

I'm trying to serve a very simple html page with one image. I'm using node.js and express. The html loads, but the image does not. Instead i am given the error GET https://localhost:3000/stockMarketPhoto.jpg 404 (Not Found) The image is in the same directory as everything else is. Somewhere I saw suggested that app.use(express.static('public')); is supposed to help with this, but no dice. I've tried both <img src="stockMarketPhoto.jpg"> and <img src="https://localhost:3000/stockMarketPhoto.jpg">. How can I get the image in my HTML page to load?
Here's the html in question
<body>
<img src="stockMarketPhoto.jpg">
</body>
Here's the javascript.
const https = require('https');
const express = require("express")
const fs = require('fs');
let app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log("listening on 3000");
});
app.get('/', (req, res) => {
console.log('connected');
res.sendFile(__dirname + '/index.html')
})
First i recommend you read this from the express docs.
Serving Static files in express
and in here:
<img src="stockMarketPhoto.jpg">
you are missing a '/' should look like this:
<img src="/stockMarketPhoto.jpg">
Your image should be inside the public folder in your app. What i do is usually put an Image, Javascript, and css folder inside my public folder and import them like this:
src='/Image/example.jpg'
src='/Javascript/example.js'
src='/css/master.css'
Basically when you tell express to serve your static files in the public folder, express then interprets the above example like this.
'public/Image/example.jpg'

Javascript and HTML Problems

having trouble getting this to run with node
const express = require('express')
const app = express()
app.use(express.static('public')) //adds content of public folder
app.get('/', function (req, res){
res.sendFile('/views/index.html', {root: __dirname})
})
app.listen(1337, function (){
console.log('lab5-server.js listening on 1337')
})
it was running perfect yesterday and now it's not. There's also an issue with the .html portion, it wont display the image I have assigned. Quick note it that I left out most of whats written below the source code for the image, it's not necessary for this question.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1> <center> Welcome to Matt's Page </center></h1>
<center> <img src = "images/AlgorithmofSuccess.jpg"/> </center>
Does anyone see where I went wrong and why the terminal is returning "unexpected token" on the javascript portion?
You should try to use the path module to help point to your public path. I can give you an example:
const path = require("path");
const app = express();
const publicPath = path.resolve(__dirname, "./public");
// We point to our static assets
app.use(express.static(path.resolve(__dirname, "./public")));
app.get("/*", (req, res) => {
res.sendFile("index.html", { root: path.join(__dirname, "./public") });
});
// And run the server
app.listen(1337, () => {
console.log(`Server running on port ${port}`);
});
Make sure that ./public or ./dist path contains your index.html
I solved this, just had to change the folder of the lab5-server.js file i was using, thanks for the help guys

Basic webserver with node.js and express for serving html file and assets

I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.

Categories

Resources