how to properly include fusioncharts.js into node express project using jade? - javascript

I tried
script(src="/fusioncharts.charts.js")
in the head of layout.jade, but it didnt work, error 404.
Then I tried via
layout.jade:
script(src="/charts")
app.js:
app.get('/charts', routes.charts);
index.js:
exports.charts = function(req, res){
res.sendFile(__dirname + "fusioncharts/fusioncharts.charts.js");
};
I get error : res.sendFile is not a function.
I have enide2015, project created with node_modules from enide.
I tried with -- router.get( ... - I got property undefined error
layout.jade:
doctype html
html( lang="en" )
head
title= title
meta( charset='utf-8' )
meta( http-equiv='X-UA-Compatible', content='IE=edge' )
meta( name='viewport', content='width=device-width, initial-scale=1.0' )
meta( name='description', content='Baking Bootstrap Snippets with Jade' )
//- Bootswatch Theme
link(href='//maxcdn.bootstrapcdn.com/bootswatch
/3.3.6/flatly/bootstrap.min.css',rel='stylesheet')
script(src="https://www.google.com/jsapi")
script(src="http://maps.google.com/maps/api/js?sensor=true")
script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js')
//***************************
script(src="/fusioncharts")
//***************************
In other words, proper way to include external js local library, not CDN source ,ideally specifically fusioncharts ? Thank you.
EDIT: OK, found the problem, when creating node express project with Enide, there's pre-set environment in app.js, setting only PUBLIC folder accessible. I got now 200 OK message while accessing fusioncharts.js file.
I am still not able to render the chart itself, rendering ? Any suggestions ?

Found this trending on Reddit - talks about using FusionCharts with Node, Express and MongoDB.
http://www.fusioncharts.com/tutorials/creating-interactive-charts-using-node-express-and-mongodb/

Related

"Stylesheet could not be loaded" error in Node/Express App

I am trying to load a stylesheet into my page through express, but there is no good reason as far as I can tell as to why it is not working. When I route to the file in a browser, I can see the CSS file, but there seems to be a problem with the app.use. Could anyone point out what I am doing wrong?
main.js
app.use('/css/stylesheet.css', function(req, res) {
let stylesheet = fs.readFileSync(path.normalize(__dirname+"/views/css/stylesheet.css"), 'utf8');
res.setHeader('Content-Type', 'application/css');
console.log(stylesheet);
res.send(stylesheet);
});
index.ejs
<link rel="stylesheet" type="text/css" href="/css/stylesheet.css">
My file directory:
.
|-views
| |-css
| | |-stylesheet.css
| |-index.ejs
|-main.js
I found the error, I set the Content-Type as "application/css" instead of "text/css", so the browser wouldn't load the css file.

HTML <script> src url no longer works after rearranging files

I'm working on a personal project in order to learn web dev, and I've run into a strange (and hopefully easily solved) problem. In my index.html file I've included a reference to a main.js file, and that's been working just fine for a while now. However, I've recently rewritten the project in Typescript and I've decided to rearrange the folder structure. The problem is that when I move my index.html file (and some other files) down one directory and append a '../' to the script's 'src' tag, I get a 404 error when the html attempts to load the script.
This works just fine:
.
|-scripts
|-Main.ts
|-Main.js
|-SlideShowView.ts
|-SlideShowView.js
|-Server.ts
|-Server.js
|-index.html -> <script src="scripts/Main.js" type="module"></script>
This does not:
.
|-scripts
|-Main.ts
|-Main.js
|-SlideShowView.ts
|-SlideShowView.js
|-services
|-Server.ts
|-Server.js
|-index.html -> <script src="../scripts/Main.js" type="module"></script>
Connecting to the site when using the second scheme gives this error:
GET http://localhost:8000/scripts/Main.js net::ERR_ABORTED 404 (Not Found)
Is index.html not allowed to look above it's own directory? Is there a permissions issue or something? It's such a simple thing that's failing to work I figure there must be something small I'm missing.
Thanks in advance for the help!
Found the answer!
After I moved index.html back to root, the problem wasn't in my html or main.js, but in the express server I was using:
import path from "path";
import express from "express";
const serverPortNum = 8000;
const htmlFile = path.join(__dirname + '/../index.html'); //Added an escape here...
// Create html server
var app = express();
app.use(express.static(__dirname));// ...but not here.
app.get('/', function(req: any, res: any)
{
res.sendFile(htmlFile);
});
app.listen(serverPortNum, function()
{
console.log("Listening! (port " + serverPortNum + ")");
});
Basically, I had changed the path to the html file correctly but I forgot to make the change in app.use() as well. Changing that line to app.use(express.static(__dirname + "/..")); corrected the problem.
This should be simple as moving the index.html file outside of both file structures
|-scripts
|-Main.ts
|-Main.js
|-SlideShowView.ts
|-SlideShowView.js
|-services
|-Server.ts
|-Server.js
|-index.html -> <script src="scripts/Main.js" type="module"></script>

CSS file path doesn't work both on localhost and in text editor

So, I'm working on URL Shortener written in JS using Node.js and Express. I've just finished front end but I have a problem with getting css to work.
My project tree looks like this:
public
css
main.css
views
index.html
app.js
In my index.html file I have my .css file linked this way
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
and it does work while making the site in Brackets editor, but when I launch localhost server CSS doesn't and I get
Cannot GET /public/css/main.css
I suppose it has something to do with my static path declared in app.js
app.use(express.static(path.join(__dirname, "public")));
because when I change the path in index.html to /css/main.css everything works on localhost but then my local text editor (Brackets) can't see that css file.
What should I do to make it work both during development in text editor and on localhost?
There are a couple of ways ( probably more ) :
Option 1
Go with your browser for debugging your application ( use only your app to see the modifications and not the brackets editor )
Option 2
Set your href="" attribute to a static location, e.g. href="localhost:8080/css/main.css". Then ( probably ) when you run your editor and the app simultaneously, you will get the same CSS file on both sides.
Option 3
Add another line of stylesheet to load them both.
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
<link rel="stylesheet" type="text/css" href="/css/main.css">
The most common way to solve this problem, usually is Option 1, so you can just don't bother about bracket's internal browser and figure out a combination with live-reload module that will duplicate the extras that you get from your editor.
browser sends a get request to fetch a CSS file, you can add the following code snippet in you code:
var fs = require('fs');
var url = require('url');
var query = url.parse(req.url, true)
var pathname = query.pathname
var filepath = "./public/"
if(fs.existsSync(filepath+pathname)){
res.end(fs.readFileSync(filepath+pathname));
}
now in the html page :
<link rel="stylesheet" type="text/css" href="css/main.css">
Explained :
the browser will send a GET request for css/main.css
and the pathname will be then css/main.css
filepath is declared as ./public/
filepath + pathname will be ./public/css/main.css
fs.existsSync will return true and write the data in response.
becauase you filepath is ./public/ only files under public directory can be send in this method so your *app.js/ file is safe.
I have written this in synchronus manner using Sync functions you can do it using asynchronus manner too.
hope this helps

Spring mvc loading JS with Uncaught SyntaxError: Unexpected token <

I'm using Spring boot. I have this structure for a simple test app:
What I do in my TestController is to get 2 path variables and load index.html:
#Controller
public class TestController {
#RequestMapping("/{vara}/{varb}")
public String index(#PathVariable(value="vara") String vara, #PathVariable(value="varb") String varb) {
return"/index.html";
}
}
and the index.html is empty, clean html page:
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
TEST
</body>
</html>
so typing localhost:8080/abbas/mirza in my browser and everything looks ok and the html page loads easily.
I have 2 js files, test.js and /js/testb.js which both have this line of code inside.
var s = {};
Now I add this
<script src="/test.js"></script>
and everything is still ok and I can view the test.js code, but when I add
<script src="/js/testb.js"></script>
the page throws an exception
Uncaught SyntaxError: Unexpected token <
and when I try to open the testb.js file it shows me this
if I move testb.js into the webapp itself, it will be loaded with no problem. I'm quite newbie using the Spring mvc and still confused with all the configuration regarding routings and accessing resources.
Any idea what I'm doing wrong?
Edit:(link to github) https://github.com/arashzz/test22
The #RequestMapping pattern you're using is so broad that the path to your JavaScript file testb.js matches it and thus the index page is served in lieu of your js file causing the syntax error to occur.
Controller:
#RequestMapping("/{vara}/{varb}")
JavaScript Path:
/js/testb.js
This matches that pattern where vara=js and varb=testb.js
Your other JavaScript file is located at /test.js and thus doesn't match the pattern and is served correctly.
Solution:
Adjust the #RequestMapping pattern to something more narrow such as:
#RequestMapping("/placeholder/{vara}/{varb}")
Try <script src="js/testb.js"></script> without /as index.html and js directory are in same directory level

How to easily pass a variable with Node.js to the view

I'm trying to learn the basics of Node.js and I can't seem to be able to simply send a variable from app.js to index.html without using Jade or other template engine.
This is my app.js
var express = require("express");
var app = express();
app.get('/', function(req, res){
//I'd like to send this as a variable instead
res.send("some text");
});
app.listen(8080);
This is my index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//I want to alert my variable here please
alert(variableFromAppjs);
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>
Is there a way to do it simply like that?
The reason you can't just "send" the variable from your app.js to index.html is because they're two separate programs. index.html is run ONLY on the client machine through the browser, and app.js is run ONLY on the server.
In order for index.html to receive data from app.js, you'll need to to use XMLHttpRequest to make a request to your Node app.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
You can then receive the data asynchronously and save it to whatever variable you want.
You will need to make sure you're using a server-side templating engine (express comes with jade support).
Use npm to install jade to your express app. and then tell express where the templates are, and, in the get route definition you must instruct express what view to use:
var express = require("express");
var app = express();
// Tell express where your templates are
app.set("views", __dirname + "/views");
// Tell express templates are jade files
app.set("view engine", "jade");
app.get("/", function(req, res) {
res.render("home", {
title: "Home Page",
body: "This is just a test..."
});
});
app.listen(8080);
when all this is setup create views/layout.jade and a views/home.jade
Home.jade will look like this:
extends layout
block content
h1= title
p A tag name followed by the equals (=) sign is like php echo
p= body
ul
li This is a hardcoded list
li With two elements
Layout.jade will look like this:
html
head
meta(charset="utf-8")
title= title
link(rel="stylesheet", href="/css/main.css")
meta(name="viewport", content="width=device-width")
body
block content
div.page-content.text-center
h1 Default content
p anything I put here will be overridden by the home.jade content block Which means that any jade view that doesn't provide a `block content` part will render this text instead.
If you create another route for example:
app.get("/default", function(req, res) {
res.render("test", {title: "Default route", body: "Whatever"});
});
an then its corresponding template views/test.jade
extends layout
p I'm not providing a `block content` so this text won't be rendered
blockquote(class="my-class", id="my-id") In jade, the very first word of a line is the tag to be used by the line, to provide attributes to a tag you use comma-separated HTML attributes in between parenthesis right next to the tag name.
And visit your route at http://localhost:8080/default You will see the default text be rendered.
I hope this is of help.

Categories