Chaplin and regions - node.js

I'd need some help in getting started with node.js and Chaplin
Here's the scenario:
Client comes to my server
I serve a static html page to the client. In this html there's a div with and id "test"
This html also launches the chaplin app
in my chaplin app, I want to be able to attach an event to the "test" div, e.g clicking the div alerts "Yeah"
How does this work?
For what I've managed to learn by trying (as I don't really find any good instructions on this chaplin..) is that I need to create regions where I then put my views into. These views can only have events inside this region. What I don't get is how do I get to use this "test" div as a region?
server
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Client
index.html
<!doctype html>
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/stylesheets/app.css">
<script src="/javascripts/vendor.js"></script>
<script src="/javascripts/app.js"></script>
<script>require('initialize');</script>
</head>
<body>
<div id="test">
</div>
</div>
</body>
</html>
routes.coffee
module.exports = (match) ->
match '', 'home#index'
home-controller.coffee
Controller = require 'controllers/base/controller'
HeaderView = require 'views/home/header-view'
HomePageView = require 'views/home/home-page-view'
module.exports = class HomeController extends Controller
beforeAction: ->
super
#compose 'header', HeaderView, region: 'header'
index: ->
#view = new HomePageView region: 'main'
home-page-view.coffee
View = require 'views/base/view'
module.exports = class HomePageView extends View
autoRender: true
className: 'home-page'
template: require './templates/home'
events:
'click "testi"': 'testEvent'
testEvent: (event) ->
alert "Yeah"
Clicking works ok in this HomePageView thing but how could I bind that event to the "test" div in my html, or how could I use already existing divs as regions?

You would add container option to your main layout view, where the value is your dom element e.g. #test. So it may look something like this.
View = require 'views/base/view'
module.exports = class HomePageView extends View
container: '#test'
autoRender: true
className: 'home-page'
template: require './templates/home'
events:
'click "testi"': 'testEvent'
testEvent: (event) ->
alert "Yeah"
I would also suggest you take a look at this project - https://github.com/chaplinjs/chaplin-boilerplate. A nice boilerplate example, should help with your understanding.

Related

NodeJS: Stylesheet not loading due to unsupported mime type

I'm making an app with NodeJS and Express, and when I start the server I get the following error:
Refused to apply style from 'http://localhost:3000/style.css' because its MIME type
('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here's my directory tree:
app:
|-node-modules
|-index.js
|-package.json
|-package-lock.json
|-views
|-index.html
|-public
|-stylesheets
|-style.css
Here's my index.js:
const express = require("express");
const app = express();
const path = require("path");
app.use("/static", express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/views/index.html"));
});
app.listen(process.env.port || 3000);
console.log("Server Is Active At Port " + (process.env.port || 3000));
And here's my index.html and style.css:
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/public/stylesheets/style.css">
</head>
<body>
<h1>Test</h1>
</body>
</html>
body{
text-align: center;
}
Please note that I'm just testing to see if the site works, and this isn't the full code for the site.
You're not showing us the full picture - how are your styles being loaded? Presumably with a <link> tag you opted not to show us. Anyhow, the express.static middleware should take care of setting the correct mime type. You probably aren't providing the correct path to the stylesheet.
Your style tag in your html should look something like this:
<!-- note the "/static" part at the beginning of the url -->
<link rel="stylesheet" href="/static/stylesheets/style.css" />
Try writing
app.use('/public' , express.static(path.join(__dirname, 'public'))); instead of app.use("/static", express.static(__dirname + "/public"));
After that in your html while linking to the css file you can write
<link rel="stylesheet" href="/public/stylesheets/style.css">
Hope this solves the issue
I think this will work. Define path like this:
const staticfiledir = path.join(__dirname,'../public')
Setup for static directories to serve
app.use(express.static(staticfiledir))

Refused to apply stylesheet because its a MIME type, running off of ATOM.io onto Google Chrome

I'm a new programmer and need some help. I'm trying to launch a website and my stylesheet won't load. The error looks like this:
Refused to apply style from 'http://localhost:3000/stylesheets/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I know that there are other similar errors reported, but I am running off of Atom.io onto a Google Chrome browser. Not sure if it has anything to do with my IDE or browser but every other solution I have seen has not worked for me. I'm running node.js on the backend and this is my code:
var express = require('express'),
`app = express(),
bodyParser = require('body-parser'),
mongoose = require("mongoose"),
passport = require('passport'),
flash = require('connect-flash'),
methodOverride = require('method-override'),
LocalStrategy = require('passport-local');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname + "/public"));
app.set('view engine', 'ejs');
//index
app.get('/',function(req,res){
res.render('home')
})
app.listen(3000, function(){
console.log("Your personal website has started")
}); `
Can anyone help me out? My front end code looks like this as well:
<html lang = 'en'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"></link>
<link href ='/stylesheets/home.css' rel ='stylesheet' type = 'text/css'></link>
</head>
Thanks!
Jake
Use this code in server file:
app.use(express.static(__dirname + '/public'));
Use this code in home.ejs file
<link rel="stylesheet" type="text/css" href="/css/app.css" />

angularjs index.html in views folder

I have little confusion. Using Nodejs
folder structure image is attached.
If I put index.html at the root of Client folder than everything is working fine.
On the other hand if I move index.html in the views folder like in the image than js files are not loading but index.html is loading.
Nodejs - server.js
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.logger('dev')); //tiny, short, default
app.use(express.methodOverride());
app.use(express.cookieSession({secret: "sdfr"}));
//app.set('views', __dirname + '/client/views/');
app.use(express.static(__dirname + '/client/views'));
});
app.js
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/',
{
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/login',
{
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
});
$routeProvider.when('/register',
{
templateUrl: 'partials/register.html',
controller: 'RegisterCtrl'
});
$routeProvider.when('/404',
{
templateUrl: 'partials/404.html'
});
$routeProvider.otherwise({redirectTo: '/404'});
//$locationProvider.html5Mode(true);
}])
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="contactManager">
<head>
<meta charset="utf-8">
<title>Angular Demo</title>
</head>
<body>
Home<br/>
Login<br/>
Register<br/>
Private<br/>
Admin<br/>
404<br/>
<div>
<div ng-view></div>
</div>
<script src="../lib/vendor/angularjs/1.1.5/angular.min.js"></script>
<script src="../js/app.js"></script>
<script src="../js/controllers.js"></script>
</body>
Currently you are NOT including the JS in express.static. The included JS sources at ../js from your index.html file go nowhere because client/views is the only directory being served by express.static.
You should just include the whole client in your static, otherwise you'll have to do include each directory into your static provider.
app.use(express.static(__dirname + '/client/views')); means you are serving anything from /client/views but nothing OUTSIDE of that directory.
app.use(express.static(__dirname + '/client/js')); would allow you to serve the JS folder, but it would be accessed at root. You can use TWO static providers but the first one will win in the event of a conflict. You could also do app.use(express.static('/js', __dirname + '/client/js')); which would all you to access client/js at yoursite.com/js but that seems strange to me.
Read up on using express.static here: http://expressjs.com/api.html#middleware

Express & EJS - layout.ejs not used

Im trying out EJS as a view engine with Express. It seems that my layout.ejs is not used. I have two views index.ejs and layout.ejs both in my 'views' folder. It seems that index.js is rendered but layout.ejs is not. The layout.ejs file should be including a CSS file but when the page is rendered in the browser this is not there. Any test test text that I place in the layout.ejs file is not output with the response.
Am I missing an additional configuration step?
Thanks!
My server.js code:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);
In my layout.ejs I am linking to a single css file which resides in the public folder.
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<div id="container">
index.html
</div>
Here's the module you need:
https://www.npmjs.org/package/express-ejs-layouts
Do the following:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));
Now the ejs engine should use your layout.
app.set('view options', { layout:'layout.ejs' });
Place layout.ejs into your views folder.
Alternately you can place layout.ejs into views/layouts folder and then use
app.set('view options', { layout:'layouts/layout.ejs' });
I have a similar issue. In my case I would rather use Jade but I have a requirement for a more "html" style template engine for a particular project. At first I considered express-partials or ejs-locals (as mentioned in a comment by Jonathan Lonowski) or even using html via the pipe or dot syntax within Jade templates (see here for more information about that option and this SO post). I am not able to introduce the additional dependencies for express-partials and ejs-locals into this project. These two projects do look good and might meet your needs.
If you do not want to use these projects, you can do something like the following:
views/layout-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
views/layout-foot.ejs
</body>
</html>
views/index.ejs (or any other page)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>
routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}
This is not an optimal solution but it works. Most of my application will be a single page app and I have some other restrictions I have to work within so this works for my needs. This may not the best solution in many cases - especially if you have complex and/or changing layouts.

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Resources