【问题标题】:Beginning jquery on node, how to fix this?在节点上开始 jquery,如何解决这个问题?
【发布时间】:2015-06-09 19:27:28
【问题描述】:

对于以下示例:

var $ = require('jquery');
$.ajax({url : 'https://api.github.com/orgs/foo/members'})
    .then(function(members) {
        for (var i in members) {
            $.ajax({url : 'https://api.github.com/users/' + members[i].login})
                .then(function(member) {
                    console.log(member.name)
                });
        }
    });

我明白了

$.ajax({url : 'https://api.github.com/orgs/foo/members'})
  ^
TypeError: undefined is not a function
    at Object.<anonymous> (sample.js:2:3)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.## Heading ##js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

不知道如何解决。有什么帮助吗?

Notice that code in this answer is not helping me.我也一样 错误或类似TypeError: Cannot set property 'cors' of undefined的东西。

1 - 我不想要关于为什么我将 jquery 与节点一起使用的建议。我有一个理由,我在 Vim 中编码,想要轻松测试几乎与我将在浏览器中放入的代码相同的代码。如果你能提供一个关于这种节点用法的教程的链接,我会很高兴(我之前在某个遥远的时间做过这个,包括节点和犀牛)。

【问题讨论】:

    标签: jquery node.js


    【解决方案1】:

    Ajax 是浏览器发出的 HTTP 请求。 Node 没有在浏览器中运行你的 JavaScript。您想使用 Node 的 http 库来发出 HTTP 请求。

    如果你觉得必须使用 jQuery 的.ajax() 函数,那么this might help you

    【讨论】:

    • 抱歉,$.ajax() 是用来做 AJAX 请求的。 Node 不在浏览器中运行,因此它需要发出正常的 HTTP 请求,而不是 AJAX 请求。问题不在于$.ajax() 是不好的做法。问题是您没有发出 AJAX 请求。
    • 为了模拟浏览器环境而隐藏模块/库并不重要。
    【解决方案2】:

    我在用jsdom(不记得我以前用过什么了):

    • npm install jsdom
    • npm install xmlhttprequest

    var jsdom = require("jsdom");
    
    jsdom.env("", ["http://code.jquery.com/jquery.min.js"], function(err, window) {
        var $ = window.$
        $.support.cors = true;
        $.ajax({url : 'https://api.github.com/orgs/foo/members'})
            .then(function(members) {
                for (var i in members) {
                    $.ajax({url : 'https://api.github.com/users/' + members[i].login})
                        .then(function(member){
                            console.log(member.name)
                        });
                }
            });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2020-06-28
      • 2021-09-17
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多