简体   繁体   中英

$ Undefined on (Node+Express+Pug+JQuery)

A Newbie question for sure, but I'd appreciate any help, as I'm completely stuck (ie, I tried everything I could find without success). When I try to use Jquery, i get "ReferenceError: $ is not defined". My project structure is:

bin/www public javascripts stylesheets routes index.js views layout.pug ... app.js

layout.pug, where I try to load CDN jquery is:

    doctype html
html(lang='en')
  head
    meta(charset='utf-8')
    title= title
    //- bootstrap CSS
    link(rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
    integrity='sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u' crossorigin='anonymous')
    link(rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css')

    //- my Styling CSS
    link(rel='stylesheet', href='/stylesheets/style.css')

  body

    block content
    script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js")
    script(src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous")
    script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'
          integrity='sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa' crossorigin='anonymous')

    script(src='/javascripts/jquery-3.3.1.js')
    script(src='routes/index.js')

My index.js file is the following:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

$(function () {
  alert('JavaScript Loaded!');
});

module.exports = router;

Finally, in my app.js file these are some relevant lines:

const indexRouter = require('./routes/index');
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Set Static Paths
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

Can anybody help me?

I think that you don't know server-side-rendering vs client-side-rendering .

Expressjs is server-side-rendering . so you don't call jQuery in index.js

If you call jQuery, you do this. var $ = require('jQuery');

reference: https://www.npmjs.com/package/jQuery#nodejs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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