简体   繁体   English

如何在Node.js和Jade中使用客户端Jquery?

[英]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. 我试图将jquery代码放在我的node.js应用程序的主页上。 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 这会生成这个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 另外,当我尝试直接在http://localhost:3000/public/javascripts/jquery-min.js访问该资源时出现错误: 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? 有什么我必须这样做,以便可以从我的应用程序访问jquery代码?

My guess is that you haven't told your Express server where to look for static files. 我的猜测是你没有告诉你的Express服务器在哪里寻找静态文件。 Add the following line to your Express configuration: 将以下行添加到Express配置中:

// 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. ...您可以通过Express访问public目录中的任何内容。

After you told Express where to look for static files like this: 在你告诉Express在哪里寻找像这样的静态文件:

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. 它将在公共文件夹中查找文件,因此如果要引用任何文件,则不必将“/ public”放在其前面。 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: 对于直接获取文件它的工作方式相同,你必须省略“/ public”并像这样使用它:

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

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 但是通过使用script(type='text/javascript' src='http://code.jquery.com/jquery.min.js')它开始工作了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM