I am trying to write a simple node.js based application which can use JustGage (JavaScript-based plugin). Following is my Node.js application.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
Following is the index.html page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Temperature Sensor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="static/resources/js/justgage.js"></script>
<script type="text/javascript" src="static/resources/js/raphael-2.1.4.min.js"></script>
<script>
window.onload = function(){
var g = new JustGage({
id: "g_a411_faculty",
value: 22,
min: 10,
max: 40,
title: "A411 - Faculty Office",
label: "Celsius",
levelColors: [
"#ffffff",
"#f9c802",
"#FF0000"
]
});
};
</script>
</head>
<body>
<div id="g_a411_faculty" class="col-sm-6" style="width:400px; height:320px"></div>
</body>
</html>
When I run the code and open http://localhost:8080 in Google Chrome, the index page shows an error that JustGage is not defined (in Developer tools). However, when I simply open up index.html (without using Node.js) in Chrome, the page works fine. Can you please help where am I going wrong?
I tried to resolve the issue by installing justgage package by
npm install justgage
However, when I write
var jg = require('justgage');
This shows a Reference Error - the document is not defined. Please help!
node.js isn't serving your static folder.
The website works when running directly from the folder as you are able to access the relative path of static/... from the same location.
When you run via node.js, you are only serving index.html and not the related assets.
Some useful ways of serving static files/folders are discussed in this thread
Related
The current solutions I know of for displaying JSCad Designs:
https://www.openjscad.org/
https://danmarshall.github.io/jscad-gallery/
https://risacher.org/OpenJsCad
https://johnwebbcole.gitlab.io/vesa-shelf/
https://joostn.github.io/OpenJsCad/
https://github.com/jscad/OpenJSCAD.org/blob/V2/packages/web/demo.html
all need quite some infrastructure to work.
https://www.openjscad.org/
is based on node The Userguide
https://www.openjscad.org/dokuwiki/doku.php?id=user_guide_website
states
The website can be integrated into an existing website.
But does not say how.
https://danmarshall.github.io/jscad-gallery/
Has it's sources at https://github.com/danmarshall/jscad-gallery. These were last modified in 2017 (some 2 years ago as of this post).
It use some dozen javascript files and jekyll to fulfill it's purpose.
Example: https://danmarshall.github.io/jscad-gallery/s-hook
The source code of a page is quite small:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSCAD Gallery s-hook</title>
<link rel="stylesheet" type="text/css" href="/jscad-gallery/site.css"/>
<script src='/jscad-gallery/browser_modules/#jscad/csg/0.3.7.js' type="text/javascript"></script>
<script src='/jscad-gallery/js/jscad-viewer.js' type="text/javascript"></script>
<script src='/jscad-gallery/js/ui.js' type="text/javascript"></script></head>
<body>
<h1>s-hook</h1>
<p>a simple S-hook design</p>
<div id="detail-viewer"></div>
<div id="inputs"></div>
<button onclick="detailView.export('stl', document.getElementById('download'))">Generate STL</button>
<div id="download"></div>
<script>
var design = {
title: "s-hook",
updated: null,
author: "Joost Nieuwenhuijse",
version: "1.0.0",
dependencies: [{"#jscad/scad-api":"^0.4.2"}],
image: "/browser_modules/s-hook/thumbnail.png",
camera: {"angle":{"x":-60,"y":0,"z":-45},"position":{"x":0,"y":0,"z":116}}
};
var detailView = new JscadGallery.DesignView();
detailView.load(document.getElementById('detail-viewer'), design, document.getElementById('inputs'));
</script>
<footer>
Jscad-gallery on GitHub
</footer>
</body>
</html>
I am looking for a (hopefully) simple solution that can be embedded in Mediawiki. For a start a plain html page with a bit of javascript would do for me.
see also:
https://openjscad.nodebb.com/topic/98/displaying-jscad-designs-in-media-wiki-or-plain-html-for-a-start
For a start I created http://wiki.bitplan.com/index.php/ParametricLampShade by simply copying the html from https://risacher.org/OpenJsCad/lampshadedemo.html.
I put the files:
csg.js
lightgl.js
openjscad.js
into the folder extensions/OpenJsCad.
With this simplistic approach i get the error:
Error in line 466: NetworkError: Failed to load worker script at http://wiki.bitplan.com/index.php/csg.js (nsresult = 0x804b001d)
The reasons seems to be in openjscad.js:
// callback: should be function(error, csg)
OpenJsCad.parseJsCadScriptASync = function(script, mainParameters, options, callback) {
var baselibraries = [
"csg.js",
"openjscad.js"
];
var baseurl = document.location.href.replace(/\?.*$/, '');
var openjscadurl = baseurl;
if (options['openJsCadPath'] != null) {
openjscadurl = OpenJsCad.makeAbsoluteUrl( options['openJsCadPath'], baseurl );
}
var libraries = [];
if (options['libraries'] != null) {
libraries = options['libraries'];
}
...
}
the openjscadurl is taken from the basepath which for Mediawiki is ../index.php.
How could I fix this?
What is the minimum set of javascript files needed and would be the proper versions of these files?
Changing the baseurl calculation to:
//alert(document.location);
var baseurl = document.location.href.replace(/index.php\/.*$/, 'extensions/OpenJsCad/');
//alert(baseurl);
fixed the issue.
See http://wiki.bitplan.com/index.php/ParametricLampShade for the result.
As a proof of concept
http://wiki.bitplan.com/index.php/Template:Jscad now has a Mediawiki Template.
I'd still like to learn about the javascript files and versions that should be used. Since the current approach use some outdated javascript files and can't even render the OpenJSCAD logo code from http://openjscad.org
The 1.10.0 version of https://www.npmjs.com/package/#jscad/web allows you to host a JsCad file with a single package. https://github.com/jscad/OpenJSCAD.org/pull/413
While this doesn't directly help you, I have a Vue component that allows you to show a JsCad file at https://gitlab.com/johnwebbcole/vue-openjscad
You may be able to use that to update your Mediawiki plugin.
J
I'm trying to learn HTML/CSS and AngularJS by making a single-page web app that will show time, weather, and other info. My goal is to be able to drag and drop these on the web page so that a user can arrange them as they see fit.
My first step is to show time, which I'm able to do (I got the code based on this code from another answer). However, it doesn't actually work on my own environment and I'm not sure if it's because my files are incorrectly linked. My directory structure looks something like this:
-- app
+ -- clock.js
-- node_modules
-- public (holds css and images)
index.html
(some other files)
As you can see in my code, I wrote <script src="app/clock.js"></script>, but when I check localhost:8080, instead of the time, I get {{ clock | date 'HH:mm:ss' }}. Is there something else I need to include in the html or js file to get Angular to start working?
var app = angular.module('test_app', []);
app.controller('updateClock', function($scope, $interval) {
var tick = function() {
$scope.clock = Date.now();
}
tick();
$interval(tick, 1000);
});
<!DOCTYPE html>
<html>
<head>
<title>TEST PAGE</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
</head>
<body>
<div ng-app="test_app">
<div class="container">
<div ng-controller='updateClock'>
<p>{{ clock | date: 'HH:mm:ss'}}</p>
</div>
</div>
</div>
</body>
<script src="app/clock.js"></script>
</html>
Edited to add server code:
// server.js
// using express
var express = require('express');
var app = express();
var port = 8080;
// route the app
var router = require("./app/routes")
app.use("/", router);
// set static files (css, images, etc)
app.use(express.static(__dirname + '/public'))
// start the server
app.listen(port,function() {
console.log('Live at port ' + port);
});
I'm very new to node, express etc. I've made a blog-app and i'm facing a problem. I'm using mongoose, node, express and ejs.
When i call
router.get('/posts', function(req, res){ Post.find({}, function(err, posts){
res.render('viewpost.ejs', {
posts
}); }); });
Everything works perfectly fine. I got my posts and css is working as well. The problem is when i call
router.get('/posts/:posts_id', function(req, res){
Post.find({_id: req.params.posts_id}, function(err, posts){
res.render('viewpost.ejs',{
posts
});
});
});
Post seems to be working but in console i got
GET /posts/posts.css 304 1.854 ms
And the viewpost.ejs looks like it's not using the css.
Server file server.js
app.use(express.static('public'))
app.use(express.static(path.join(__dirname, 'public/css/')));
app.use(express.static(path.join(__dirname, 'public/img/')));
viewpost.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
<link rel="stylesheet" href="style.css">
<script src="/bower_components/jquery/dist/jquery.js"></script>
</head>
<body class="cyc">
<% include ./partials/navbar.ejs %>
<%= posts %>
</body>
</html>
So when i use route without req.params everything seems to be working
ok. When i call it with any param my css file is not working.
<link rel="stylesheet" href="style.css"> tries to load style.css from the same path where the HTML page is. So, for /posts, it will try loading /style.css and for /posts/1, it will try to load /posts/style.css. But the latter matches your /posts/:posts_id endpoint, so that gets called instead with posts_id == 'style.css', which is nonsensical.
The solution is quite simply to make the link absolute:
<link rel="stylesheet" href="/style.css">
I was facing the same issue,but finally I solved it.
Do Following:
In Your HTML or EJS File write:
<link rel="stylesheet" href="../style.css">
in head section,it will work for both /post and /post:id
I have a problem loading external files into my index.html. My stylesheet as well as my JS files do not show up at all (Error 404 - Not Found). My directory structure is as follows.
My index.html is:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Orders and Customers</title>
<link rel="stylesheet" type="text/css" href="./assets/css/stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.min.js"></script>
<script src="./../app/app.js" type="text/javascript"></script>
<script src="./../app/controllers/customer/CustomerController.js"></script>
<script src="./../app/controllers/order/OrderController.js"></script>
<script src="./../app/services/customer/CustomerService.js"></script>
<script src="./../app/services/order/OrderService.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
This is what Chrome shows:
My server.js is:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
require('./server/config/mongoose.js');
require('./server/config/routes.js')(app);
app.use(express.static(path.join(__dirname, './views')));
app.listen(8000, function() {
console.log('Listening on Port 8000');
})
Any help is greatly appreciated!
Try this
in server.js
var router = express.Router();
router.use(express.static(path.resolve(__dirname, "../app")));
in index.html
<script src="/app.js" type="text/javascript"></script>
<script src="/controllers/customer/CustomerController.js"></script>
<script src="/controllers/order/OrderController.js"></script>
<script src="/services/customer/CustomerService.js"></script>
<script src="/services/order/OrderService.js"></script>
Router is middle-ware for capture * path.
For example, /service/* matches all requests under service path.
so I changed your code as to handle all resources under "/app" folder. (eg: /app/app.js, etc)
path.resolve changes path from relative to absolute.
it means that you can add another current working directory.
path.resolve(__dirname, "../app") add "/app" from current working directory (views). it parsed from "views/../app" to "/app"
(Reference) Path.resolve
The relative paths
<script src="./../app/app.js" type="text/javascript"></script>
etc, are pointing to the wrong directory.
Use the Network tab in your browser developer tools, to check what exact requests are going out.
If the whole app directory is public (Which, in my opinion, should not be the case), "./../" will refer to the views directory.
Single . refers to the current directory, which in this case is, the one containing your index.html. Double .. refers to the directory above it, which here is views.
Rather than
<script src="./../app/app.js" type="text/javascript"></script>
Try using the full path:
<script src="/app/app.js" type="text/javascript"></script>
<script src="/app/controllers/order/OrderController.js"></script>
Try this
app.use(express.static(path.join(__dirname, 'views')));
and just use
<link rel="stylesheet" type="text/css" href="assets/css/stylesheet.css">
Thanks to SeongHyeon, I was able to figure out the solution to my problem. I really appreciate your guys' help. I'd like to elaborate more on this just for my own reference.
When declaring your static path in express, you don't need to reference anything relative to the file that you're trying to import from. Instead, you simply reference the file from the static path that you've declared.
I am new to javascript language.
I have created an application in Bluemix. To this application I have attached SQL database service. From the applications index.html, I am trying to call function "TryConnect()" which has the logic to connect to the SQL database.
Below is the implementation of TryConnect:
this.TryConnect = function(){
var mysql = require("mysql");
var conn = mysql.createConnection({
host: "127.0.0.1",
user: "user",
password: "password",
database: "SQL Database-ox"
});
conn.connect(function(err){
if(err){
console.log("Error connecting to DB");
return;
}
console.log("Connection Established");
});
}
upon running this I am getting below error:
Uncaught Error: Module name "mysql" has not been loaded yet for context: _. Use require([])
My index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<title>NodeJS Starter Application</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="stylesheets/style.css">
<script data-main="db" src="require.js" ></script>
<script type="text/javascript" src="db.js" ></script>
<script type="text/javascript">
function ConnectToMySQL(){
alert("connect");
TryConnect();
alert("connect end");
}
</script>
</head>
<body>
<table>
<tr>
<td style= "width:30%;">
<img class = "newappIcon" src="images/Calendar.jpg">
<td>
<h1>Hello!</h1>
<p>Welcome to Calendar sync application.
This application synchronizes all your events, meetings and favourites.
</table>
<input type="button" onClick="ConnectToMySQL()" value="Connect to DB"/>
</body>
</html>
Module name "mysql" has not been loaded yet for context: _. Use require([])
Because on your code:
var mysql = require("mysql");
Quick Fix
Do what the error asks you:
require(["mysql"],function(mysql){
/// your code
});
Long term
This and other things are discussed here : http://requirejs.org/docs/start.html
Recommend using define in the long term.
Please include node.js which will have "mysql" declaration so when you use require("mysql") javascript engine loads the deceleration from the given libraries.
Please refer to below links.
https://github.com/felixge/node-mysql
MySQL requirements for examples
Try adding this to your code, it worked for me :
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}