How do I include the link for leaflet in my webserver? - html

I want to create a website with html/css/javascript for the frontend and c++ for the backend. (The c++ file is supposed to calculate the distance between two nodes on a map, created with leaflet.) Both, the html and the c++ file are finished I "just" need to connect them somehow.
I tried to create a http webserver with node.js by the help of this post.
My problem now is: the link for leaflet (javascript and css) that I have to include in my index.html file doesn't work / the map won't show on the website.
Is there a way to workaround this problem?
My index.html file contains this:
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
<link rel="stylesheet" href="/static/main.css">
<script src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
<script src="/static/main.js" type="text/javascript"></script>
My server.js file contains this:
//Create server
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static('public'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(3000);

Related

Trying to load my html file using nodejs to create login page

I am trying to use node.js to run a html file. I already have a login.html and styles.css for for the login page but now I don't know how to use the node js file to run my login.html page. I follow this youtube tutorial to make the a login authentication. It seems to have everything needed but now I dont know how to use it in my login.html file.
I need help modifying this so that I can run my login.html file.
index.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const postRoute = require('./routes/posts');
//Import Routes
const authRoute = require('./routes/auth');
dotenv.config();
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
//Middleware
app.use(express.json());
//Routes Middlewares
app.use('/api/user', authRoute);
app.use('/api/posts', postRoute);
// start listening
app.listen(3000, () => console.log('Server up and running port:3000'));
I am new to node.js and am completely lost on how to solve this problem.
you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)
Second you can response with the HTML file like this: (works only with express and you have express)
app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});
How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:
(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)
//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');
//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));
//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));
//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');
//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})
I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.
EJS:
put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.
*notice you dont need to write ./public in the route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>
<script src="/js/someJsFile.js"></script>
</body>
</html>
the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.
For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.
You can try to use some template engines like Handlebars. https://youtu.be/1srD3Mdvf50 You can try to follow this tutorial in order to load some html from the server side. Then you can use different selectors in order to interact with DOM elementa

CSS won't load in hbs file for some reason

so I have a very basic file structure going but for whatever reason I cannot get the css to show up in the project when I run it on the localhost. everything else except the css loads here's the structure
enter image description here
I have tried all kinds of path files and have just resorted to straight up copying the entire file path into the relevant parts but still that does not work. I am calling everything from the index.js file.
here's the code for that
const path = require('path');
const express = require('express');
const hbs = require('hbs')
const app = express();
const config = require('./config/request');
const publicDirectoryPath = path.join(__dirname, 'public')
// it was ../public but that did nothing
// also ./public/
// also ../public/
// also /public/
// also public/
const viewsPath = path.join(__dirname, './templates/views')
const partialsPath = path.join(__dirname, './templates/partials')
// error handler
app.use(function(req, res, next) {
if(config.MARKETPLACE_ID === '' || config.SECRET === '') {
res.send('MarketplaceId and secret must be set with your marketplace API credentials');
} else{
next();
}
});
app.set('view engine', 'hbs')
app.set('views', viewsPath)
hbs.registerPartials(partialsPath)
app.use(express.static(publicDirectoryPath))
app.get('', (req, res) => {
res.render('index')
})
app.listen(process.env.PORT || 3000, function(err, req, res) {
if(err) {
res.send('There was no endpoint listening');
} else{
console.log('server started on port: ', (process.env.PORT || 3000));
}
});
css file (it's VERY, VERY complicated so take your time reading through it)
.main-content {
background-color: purple;
}
index.hbs file
<!DOCTYPE html>
<html>
<head>
<title>marketplace</title>
<link rel="stylesheet" src="/literally/the/file/path/I copied/from visual studio code/public/css/styles.css" >
I even put the file into the terminal to get the exact address cause I was convinced I was spelling something wrong
unless all the possible tools used to determine file path on my Mac are wrong then this is the correct file path.
</head>
<body>
<div class="main-content">
so yeah. the index.hbs page should have a purple background. it used to say something about there being an error loading the css file cause of the MIME type or something but I've basically played around with it and got that to go away. now there is no background. no css loaded. and nothing in the console about an error or file not loading. so what gives?
at one point I was trying all of these to load in my css
<link rel="stylesheet" type="text/css" src="actual path copied from the terminal the path is 100% correct>
<link rel="stylesheet type="text/css" href="100% correct file path">
I had the same issue, so solve it you should put in the link src only "/css/styles.css".
<link rel="stylesheet" href="/css/style.css">
I hope it works for you as well.

Server or HTML isn't displaying CSS (but works when opening HTML file)

I've been trying to learn how to set up a node.js server for a simple website for the first time and am encountering some strange behavior. When I open my index.html file from my computer it opens up perfectly with all of the CSS working properly. However I then set up a basic node.js server and when accessing the index.html file through my browser it only loads the html but not the CSS.
I'm extremely new to this so haven't been able to try much, also because the code is extremely simple so can't see what's missing (I tried following this tutorial if that helps). I also found another question that seemed similar on here but it didn't have an answer and didn't really help, I did check that all the files are UTF-8.
The HTML:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1>A headline</h1>
</body>
</html>
And the node.js server:
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
const myReadStream = fs.createReadStream(__dirname + "/index.html", "utf8");
myReadStream.pipe(res);
});
server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");
When I include the CSS within <style> tags and directly in index.html it does work, but I've tried putting <link rel="stylesheet" href="styles.css" type="text/css"> between <style> tags and that still doesn't (it would also be weird if that's necessary seeing as it displays perfectly when I simply open the html file). I've also tried removing type=text/css but that didn't seem to change anything. Any help would be much appreciated!
You need to serve the style.css as well. You are serving the index.html but in the index.html it is hitting http://127.0.0.1:300/style.css when the request is coming to your app it is STILL serving the index.html file. (You can confirm this in Network pane of developer tools)
const server = http.createServer(function (req, res) {
const url = req.url;
if (url === '/style.css') {
res.writeHead(200, { 'Content-Type': 'text/css' }); // http header
fs.createReadStream(__dirname + "/style.css", "utf8").pipe(res);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
fs.createReadStream(__dirname + "/index.html", "utf8").pipe(res);
}
})
Note: It is very easy to achieve this using express, probably the most popular nodejs package.

Nodejs Express not loading script files

I am trying to run a angular app thru node-express.
1 File Structure
AngularNode
public
/core.js
/index.html
project.json
server.js
2 server.js
var express = require('express');
var app = express();
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// listen (start app with node server.js) ======================================
app.listen(8000);
console.log("App listening on port 8000");
3 index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="./core.js"></script>
........
4 core.js
angular.module('MySystem',[])
.controller('AppController',['$scope',function($scope){
$scope.Name ="Testing Text";
}]);
When I tried to run this app using node server.js this, index.html file is getting loaded properly, however this is not detecting or loading core.js file. and I am getting following errors
Uncaught SyntaxError: Unexpected token < core.js:1
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381) angular.js:38
Now, when I open index.html file directly from explorer, this is working OR when same code I move from core.js to inline html, under <head> with <script> block it is working.
I am not sure, why core.js not detecting or loading when I run thru node.
Got the Solution with few modifications:
1 Added line in server.js
app.use(express.static(__dirname + '/public')); after line
var app = express();
2 Case correction(Capital 'f') for function from res.sendfile('./public/index.html'); to res.sendFile('./public/index.html');
Now I can see core.js is detected and working fine.
The app.get('*', function(req, res) { is a catch all rule for all get request and will also match the ./core.js request. So for the ./core.js your express app will also send the html file.
You should use express.static instead:
var express = require('express');
var app = express();
app.use(express.static('./public'));

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.