3

I'm new in node.js.My express.js app structure:

| my-application
| -- app.js
| -- node_modules
| -- public
| -- models
     | -- users.js
| -- routes
     | -- index.js
| -- views
     | -- index.ejs

I try to use $.inArray() function. I installed https://www.npmjs.com/package/jquery package.

routes/index.js

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

router.get('/', function(req, res, next) {
  var arr = [ 'a','b','c' ];
  $.inArray('a',arr);

  res.render('index',{
      title:'home'
  });
});

module.exports = router;

it gives me following errors:

undefined is not a function
TypeError: undefined is not a function
at c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\routes\index.js:12:7
at Layer.handle [as handle_request] (c:\Users\Ahmed Dinar\Dropbox     \IdeaProjects\justoj\node_modules\express\lib\router\layer.js:95:5)
at next (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\layer.js:95:5)
at c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\index.js:277:22
at Function.process_params (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\index.js:330:12)
at next (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\index.js:271:10)
at Function.handle (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\index.js:176:3)
at router (c:\Users\Ahmed Dinar\Dropbox\IdeaProjects\justoj\node_modules\express\lib\router\index.js:46:12)

How can i use jQuery functions in routes also in my models.

Thanks in advance.

Ahmed Dinar
  • 80
  • 2
  • 9

2 Answers2

1

jQuery does not work very well with the Node JS, I recommend to use Lodash - https://lodash.com/ .

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

router.get('/', function(req, res, next) {
  var arr = [ 'a','b','c' ];
  var inArray = _.indexOf('a',arr) > 0;

  res.render('index',{
      title:'home'
  });
});

module.exports = router;
Bartosz Czerwonka
  • 1,631
  • 1
  • 10
  • 11
0

Keep in mind that jquery require a document window for properly work.
You could maybe use jsdom for that:

var jsdom = require("jsdom"),
    $     = require('jquery')(jsdom.jsdom().parentWindow);

Take a look at:
Error: jQuery requires a window with a document

Community
  • 1
  • 1
TGrif
  • 5,725
  • 9
  • 31
  • 52