making jquery work in expressjs app - express

It is a noobish question.
I am writing an expressjs app. I am not able to get jquery or bootstrap working.
// app.js
app.use(express.static(__dirname + '/public'));
Also tried
app.use(__dirname + '/public');
or
app.use(path.join(__dirname + '/public'))
or
app.set(__dirname + '/public');
or
app.set(path.join(__dirname + '/public'))
// views/home.html
<head>
<script src="/js/jquery.min.js"></script>
</head>
<body>
<script>
$(function(){
alert('hello');
});
</script>
</body>
//public>js>jquery.min.js
It is not working. I am using express 4.
Template works fine other than jquery
I have a need for this to work offline while writing this app, so can not use CDN
DIRECTORY STRUCTURE
app.js
views
--layouts
--partials
public
--js
----jquery.min.js
Using 'hbs' package, handlebars for templating
Thanks

Looks to me like you shouldn't be able to reach your view with your current setup. When you say app.use(express.static(__dirname + '/public'));, you are saying that when you hit http://{hostname}:{portNumber}, you'll be served content from the the /public folder. You shouldn't be able to access any resources on your file system that do not fall within the /public folder. So maybe if you set up a folder structure like:
app.js
--public
----views
------layouts
------partials
------home.html
----js
------jquery.min.js
that I think would work (assuming that your view.html still points to jquery.js in the folder structure correctly).

Related

How do i correctly reference Vue.js node_module from electron-forge boilerplate?

This is a rookie question. I'm trying to take some baby-steps into Electron, Vue, Webpack, and Node. To that end, I've used electron-forge to spool out a boilerplate project as a starting point, like this:
npx create-electron-app my-project --template=typescript-webpack
After the project has been created everything (seemingly) works as expected. If I make any edits I can see webpack is invoked and reloading the content reveals my edits. So far so good.
My next step was to introduce the simplest Vue.js 'hello world' content I could. First, I install Vue.js using NPM, like this:
npm install "vue"
I then edit the boilerplate index.html to look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<script src="../node_modules/vue/dist/vue.js"></script>
</head>
<body>
<h1>💖 Hello World!</h1>
<p>Welcome to your Electron application.</p>
<div id="vue-app">
{{ message }}
</div>
<script>
var app = new Vue({
el: '#vue-app',
data: {
message: 'This message is from Vue!'
}
})
</script>
</body>
</html>
Which does not work. If I change the script tag to use the CDN for the Vue.js script (instead of the node_modules folder), everything works as expected.
My conclusion is that although I can reference Vue.js in my node_modules folder at design time that location does not exist in my output at run time. I'm not certain if that is due to how webpack is configured, or due to how electron works - but it strongly implies there must be something I need to do, either programmatically or via the webpack configuration to properly reference the script.
So what is the right way to 'reference' the local Vue.js script?
Thanks!
You need to reference vue via some bundler like webpack (otherwise, like you said, it is not available at runtime). Your method won't work because the generated file structure isn't the same as the one you have during 'design time'
Here's an example with vue-cli which sets up a starter project:
npm i -g #vue/cli
vue create project-name
cd project-name
vue add electron-builder
npm install
Done. Your project is operational.
With one little caveat you would encounter later, if you are using vue-router. Add the following in router.js (it changes router mode to hash instead of history so it works with electron).
export default new Router({
mode: process.env.IS_ELECTRON ? 'hash' : 'history',
})
As a sidenote, vue-cli abstracts away a lot of config. If you ever get lost, just print it out with
vue inspect > ./app/inspect.js.md
(The part after > means save to the named file, otherwise it would print it out in your console.) Check it out, that's the correct set up you're looking for, just auto created with vue-cli.
Also, check out the generated /public/index.html, it has no mention of importing vue ;)
Best of luck
After some tinkering, I came up with this solution:
The HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>💖 Hello World!</h1>
<p>Welcome to your Electron application.</p>
<div id="vue-app">{{ message }}</div>
</body>
</html>
I then added an import statement to the electron-forge boilerplate renderer.ts, like this:
import './vueapp.js';
and finally, I created a new script file called vueapp.js like this:
import Vue from 'vue/dist/vue.js';
var app = new Vue({
el: '#vue-app',
data: {
message: 'Hello Vue!'
}
});
I welcome feedback and comments; this may or may not be the correct approach and would love to hear how others have done this.

include client side js in express.js

I've build a new app with an express-generator so i've got public dir with javascripts i guess for a client side. But i can't get access to this files.
My app.js has for an absolute path
app.use(express.static(path.join(__dirname, 'public')));
But when i put on my index.html page on the bottom of the body like this
<script type="text/javascript" src="/javascripts/main.js">
i've got an error inside a console with a 404 regarding to this script.
you need to install stylus and nib npm modules
var express = require('express')
, stylus = require('stylus')
, nib = require('nib')
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
I am developing something similar. I have my javascript files inside js folder in public folder. This is my link to javascript and I am not getting any error:
<script src="js/options.js"></script>
I think you needed to remove a common slash in "src" tag or properly close the "script"

Server Rendering SyntaxError with React/Redux/Express

I'm trying to get my app rendering from the server and so was trying to implement the ServerRendering example from here: http://redux.js.org/docs/recipes/ServerRendering.html
I can successfully run server.js but I get an "Uncaught SyntaxError: Unexpected token <" error # bundle.js:2 once I load up localhost. I believe it has to do with the renderFullPage() function:
function renderFullPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
<script src="/dist/bundle.js"></script>
</body>
</html>
`
}
If I remove the line <script src="/dist/bundle.js"></script> the error goes away, but then the counter doesn't work.
Here is the bundle.js that the error references:
bundle.js
It should be referencing bundle.js in my dist folder but it's not for some reason? If I make an index.html file exactly the same as what renderFullPage is returning, except getting rid of ${html} and
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
then the counter works fine. When I do the server side rendering it seems like the client can't find the bundle.js code so creates one that has the exact same code as what it received from the server, and so there is an error as it runs into html when it's expecting javascript.
It's because your bundle.js contains HTML rather than your client-side scripts. Are you using a catch-all route and not letting it load your static assets? Your express.static middleware use call should go before this bit of code (middleware order matters).

How can I make Aurelia routing work when the application is not at the root of the host

I am building an Aurelia application that will not live at the root of the web site. Its URL will be something like this http://mycompany.com/neatoApp.
I have a route configuration that looks like this
{route:['','index'], name:'index',moduleId:'index' nave:true, title: 'neato app home'},
{route:['news'], name:'news',moduleId:'news' nave:true, title: 'neato app news'}
I have System.js configured so that it knows /neatoApp is the baseURL and it downloads all the scripts and things properly.
I have a <base href="/neatoApp" /> element in the head of my app html and I'm using pushState for routing.
The problem is when I navigate to mycompany.com/neatoApp Aurelia reports 'Route not found: /neatoApp'
Router has a baseUrl property that doesn't seem to matter what I set its value to because the route recognizer doesn't use it.
I really don't want to put neatoApp in all my routes for a few good reasons: As the app gets deployed in various places (dev, test, etc) that base path will change making that a headache to maintain. It's not the developers responsibility to know where the app is going to be deployed in various environments and it's not the operations guy's responsibility to update the code to include that base URL when he deploys it. When I do include neatoApp in the routing config it makes navigating behave strangely like generating a link that points to /neatoApp/neatoApp.
Does anybody have a solution to this problem?
I have created a plunker to demonstrate the issue: http://plnkr.co/edit/HPEzClAlncvQkSzjw6ph?p=preview
Check out this plunker to see what needs to be done:
http://plnkr.co/edit/0j6vhbTf4LZw4vOLOUka?p=preview
When you are doing something like a virtual directory where your site looks like this http://mywebsite/subfolder you want to preface your routes, stylesheets, and the baseURL in config.js to have "./" for example:
baseURL: "./"
And index.html would typically look like this:
<script src="./jspm_packages/system.js"></script>
<script src="config.js"></script>
Same with app.js which should look like this:
{ route: "", moduleId: "./src/routes/home", title: "Home", nav: true, name:"home" },
If you are publishing to the root of a web site then you can drop the "./" and just use "/" although technically you can leave the routes with "./" and just change the baseURL and it will still work.
For my MVC 5 app, I use this in my Index.cshtml:
<script src="~/jspm_packages/system.js"></script>
<script>
System.config({ baseURL: "#Url.Content("~/")" });
</script>
<script src="~/config.js"></script>
<script>
System.import('aurelia-bootstrapper');
</script>
And have commented out the baseUrl in config.js. BaseUrl needs to be set in the first call to System.config().
System.config({
//baseURL: "./",
defaultJSExtensions: true,
...

Rails 3 Best Prototype + JQuery Solution

I have a website that is rendering a prototype based calender on 90% of the pages. I'm also looking at using the Uploadify module for handling multiple uploads with Paperclip. As you know, Paperclip and JQuery don't play nicely and a lot of the solutions I've tried such as NoConflict hasn't worked for me I still get the "not defined" errors in firebug all over the place. I'm wondering what the best way for me to approach adding this JQuery module that will be very localized in a largely Prototype-based application. I've considered switching my Prototype code with JQuery but I've yet to see a better JQuery solution for this particular calendar plugin that I'm using.
Use a proper structure for noConflict.
<script src="prototype.js"></script>
<script src="someprototypeplugin.js"></script>
<script src="jQuery.js"></script>
<script src="uploadify.jquery.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function($){
$("#someelement").uploadify();
});
</script>
If this doesn't answer your question, please provide more(some) code.
Edit for comments:
Just run the $.noConflict() immediately following your jQuery plugins, and then use jQuery instead of the $ variable throughout your JS files.
<script src="prototype.js"></script>
<script src="someprototypeplugin.js"></script>
<script src="jQuery.js"></script>
<script src="uploadify.jquery.js"></script>
<script>
$.noConflict();
</script>
sample js file:
(function($){
// since we passed a reference to jQuery to this anonymous
// function and accepted it as a parameter named "$", we can
// safely use "$"
$("#target").uploadify();
})(jQuery);
If you need a document ready, you can do it this way:
jQuery(document).ready(function($) {
$("#target").uploadify();
});