【问题标题】:jQuery functions not working on express.js routes in node.jsjQuery 函数不适用于 node.js 中的 express.js 路由
【发布时间】:2016-01-16 02:37:45
【问题描述】:

我是 node.js 的新手。我的 express.js 应用程序结构:

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

我尝试使用 $.inArray() 函数。我安装了https://www.npmjs.com/package/jquery 包。

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;

它给了我以下错误:

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)

如何在我的模型中的路由中使用 jQuery 函数。

提前致谢。

【问题讨论】:

    标签: javascript jquery node.js


    【解决方案1】:

    jQuery 不能很好地与 Node JS 配合使用,我建议使用 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;
    

    【讨论】:

      【解决方案2】:

      请记住,jquery 需要一个文档窗口才能正常工作。
      你也许可以使用 jsdom

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

      看看:
      Error: jQuery requires a window with a document

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-29
        • 2017-01-24
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        相关资源
        最近更新 更多