Javascript and HTML Problems - javascript

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

Related

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

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

Express static work only with filename index.html

So i have a problem with my static files. Here's my code:
const express = require ('express')
const app = express()
app.listen(4040,() => console.log("on"))
app.use(express.static(__dirname + "/public"))
Everything works. Until I change html file name in public folder
It works if it's index.html but doesn't if it's about.html or everything else.
My folders are like that:
📂Main
📂node_modules
📂public
📂assets
style.css
index.html/about.html
main.js
package-lock.json
package.json
Route must be specific, "/" for "index.html" & "/about" for "about.html". If you change from index.html to home.html, make sure your main.js (server) also follows.
const express = require("express");
const path = require("path");
const app = express();
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "public/about.html"));
});
app.listen(4040, () => console.log("on"));
index.html (http://localhost:4040/)
<h1>HOME PAGE</h1>
about.html (http://localhost:4040/about)
<h1>ABOUT PAGE</h1>
Hey I believe I might know what's going on but wanted to clarify, you are wanting to serve multiple static files one "index.html" and another "about.html" and it's only working for the one called index.html? If this is the case this is because it defaults to reading the index.html file if it is present, the solution to this may be to rename your index.html to something else such as main.html, and see if that works properly.

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.

Implement Posted Form from NodeJS into HTML

I recently switched from starting to learn PHP to NodeJS since I have more knowledge in JS. My question is how do I display posted form data into a HTML File?
server.js
const app = require('express')(),
bodyParser = require('body-parser'),
path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'html/index.html')));
app.post('/student', (req, res) => res.send(req.body.user.name));
app.listen(3000, (req, res) => console.log('Listening on port 3000.'));
html/index.html
<body>
<form method='post' action='post'>
<input type='text' name = 'user[name]'>
<input type='submit' value='submit'>
</form>
</body>
However in the post method, I want to send a HTML file, instead of req.body.user.name which I could obviously do like I did on the home page (/), I want to be able to include some variables into the new HTML File, maybe something looking along the lines of:
<body>
<h1><? req.body.user.name + 's page. ?></h1>
<!-- rest of code -->
</body>
I use ejs template for this purpose and it is very easy to use.
First of all, download ejs with npm install ejs -s and create a views folder inside your main directory. Inside that folder, create a normal html file but this time with an extension of .ejs.
App Directory
-views/myFile.ejs
/post.ejs
-html/index.html
-server.js
Now let's go to your server.js file. You need to use app.set('view engine', 'ejs') to run ejs. When you do res.render() you don't have specify the path because the program already looks for views/ folder in the main directory.
const app = require('express')(),
bodyParser = require('body-parser'),
path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('myFile.ejs', {username: 'myUser'}));
app.post('/student', function(req, res){
var username = req.body.user.name;
res.render('post.ejs', {user: username});
});
app.listen(3000, (req, res) => console.log('Listening on port 3000.'));
This is our sample myFile.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><%=username%></p>
</body>
</html>
And this is our sample post.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><%=user%></p>
</body>
</html>
You should use some template engine, there is tutorial on express page https://expressjs.com/en/guide/using-template-engines.html.
There is always possibility that you can write your own module for handling this.
You can also install express generator
npm install express-generator -g
then call:
express
Thanks to this you will setup express project with jade as template engine(it is default), it should allow you to progress further.

Way to avoid Express.Js behaviour of adding page url to file path

I am serving my front end code using node.js and express.js.
Here I'm facing an issue with my file path I provided in script src on different page URLs.
my project file structure is as follows:
react_jsx/
dst/
index.html
styles.css
main-62a2a28f9255e698905d.js // creating this file using a bundler.
Both styles.css and main-62a2a28f9255e698905d.js are adding to index.html dynamically using webpack bundler. But adding correctly as
<link href="style.css" rel="stylesheet"></head> and <script type="text/javascript" src="main-62a2a28f9255e698905d.js"></script>
Node server code is as follows:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.resolve(__dirname, 'react_jsx/dst')));
app.use(express.static(path.resolve(__dirname)));
// app.use('/react_jsx/dst',express.static(path.join(__dirname, '')));
app.use(express.static(path.join(__dirname, ' ')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'react_jsx/dst/index.html'));
});
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
The page is working fine on the base URL. ie., on localhost:9000.
But when I'm changing the page URL, the path to the files also changes. Suppose if the page Url is localhost:9000/app/login the path to my styles.css and main-[hash].js also changes.
The file path becoming localhost:9000/app/login/styles.css and localhost:9000/app/login/main-[hash].js
How can I resolve it? I went through a lot of SO answers and resolved issue with some other file paths, but couldn't resolve issue with files that located in the same folder of index.html
I think,you can use routing.
Like :
var router = express.Router();
app.use('/app/login', router);
Give relative path from domain root in the html as shown below.
<link href="/style.css" rel="stylesheet"></head>
<script type="text/javascript" src="/main-62a2a28f9255e698905d.js"></script>
Add this to the webpack config
output: {
publicPath: "/"
}

Categories

Resources