BigBoy1337
BigBoy1337

Reputation: 4963

How to use client side Jquery with Node.js and Jade?

I am trying to put jquery code on the home page of my node.js app. This is what I have so far:

  script(type='text/javascript' src='public/javascripts/jquery-min.js')
  script.
    $( document ).ready(function() {
      alert('hello');

    });

which generates this html

<script type="text/javascript" src="public/javascripts/jquery-min.js"></script>


<script>$( document ).ready(function() {
  alert('hello'); 

}); 

</script>

yet I get no alert when my app starts. Additionally, when I try and visit that resource directly at http://localhost:3000/public/javascripts/jquery-min.js I get an error: Cannot GET /public/javascripts/jquery-min.js

Is this expected? Is there something I have to do so that the jquery code is accessible from my app?

Upvotes: 3

Views: 11150

Answers (3)

Dani&#235;l J
Dani&#235;l J

Reputation: 107

After you told Express where to look for static files like this:

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

It will look for files in the public folder, so if you want to reference any files you don't have to put "/public" in front of it. So this WON'T work:

script(type='text/javascript' src='public/javascripts/jquery-min.js')

But this will:

script(type='text/javascript' src='javascripts/jquery-min.js')

For GETing the files directly it works the same, you have to omit "/public" and use it like this:

http://localhost:3000/javascripts/jquery-min.js

Upvotes: 1

Jorge Aranda
Jorge Aranda

Reputation: 2080

My guess is that you haven't told your Express server where to look for static files. Add the following line to your Express configuration:

// Assuming you have a line such as var app = exports.app = express();
app.use(express.static(path.join(__dirname, 'public')));

...and anything you put in the public directory will be accessible through Express.

Upvotes: 3

BigBoy1337
BigBoy1337

Reputation: 4963

well I am not sure why the resource isn't available. But by using script(type='text/javascript' src='http://code.jquery.com/jquery.min.js') It started working

Upvotes: 0

Related Questions