Friday, 9 June 2017

I want to use JQuery in Node.js and EJS but $ is not defined

I want to use JQuery so I did like this.

  1. npm install jquery
  2. modify package.json

But it still doesn't work.

and this is .ejs page

<html>
<head>
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<%
    $(".btn").click(function(){
        window.location.href = "/main";
    });
%>
</head>
<body>
    //display something
</body>
</html>

and this is app.js

var express = require('express');
var $ = require('jquery')(window);
var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('ejs', require('ejs').renderFile);

var server = app.listen(8080);

app.use(express.static('public'));
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist'));

var router = require("./routes/index.js")(app);

the error code is,

$ is not defined

how can I fix it?



via Johannes Lee

No comments:

Post a Comment