【问题标题】:jQuery.ajax() in node.js?node.js 中的 jQuery.ajax()?
【发布时间】:2012-01-28 03:46:30
【问题描述】:

是否可以在 node.js 中完全按照语法方式使用 jQuery.ajax()?

我正在尝试与 node.js 共享非 UI 浏览器代码。我不想用我自己的包装器替换所有现有的函数调用。

目前,当我尝试它时,默认情况下会显示“无传输”,因为 jQuery 会进行域检测。如果我通过设置jQuery.support.cors 将其关闭,它会说 XMLHttpRequest.open() 不可用。

【问题讨论】:

  • 使用 Node 中的小型 HTTP 客户端覆盖 jQuery 的 Ajax 方法比替换代码中的所有现有调用更好,但仍然很麻烦。
  • #380 引用了这个问题。刚刚更新了我的 nq 包来解决这个问题。

标签: jquery node.js


【解决方案1】:

如果您想要确切的 jQuery.ajax 语法,请尝试 https://github.com/driverdan/node-XMLHttpRequest

但如果你真的可以控制你调用 ajax 的目的,你应该使用 node 的 http.request 或像 request 这样的模块

【讨论】:

【解决方案2】:

我能够使用 XMLHttpRequest 模块解决“无传输”问题,如下所示:

var $ = require('jquery'),
    XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

$.support.cors = true;
$.ajaxSettings.xhr = function() {
    return new XMLHttpRequest();
};

【讨论】:

    【解决方案3】:

    还可以考虑 najax,它是节点请求模块的包装器,它允许服务器端请求的 jquery 样式语法

    https://github.com/alanclarke/najax

    var najax = require('najax');
    najax('http://www.google.com', function(html){ console.log(html); });
    najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); });
    najax({ url:'http://www.google.com', type:'POST', success: function(html){ console.log(html); });
    najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){});
    
    najax.get, najax.post, najax.put, najax.delete...
    

    【讨论】:

    • 这将我引向 jajax 和 djax,它们没有依赖项(尤其是笨重的 lodash),因此它们更适合 browserify 项目。
    • 我最终没有找到适合我需要的 jQuery.ajax 等价物。 djax 不支持相当方便的 complete 处理程序,所以我决定使用未来技术:github.com/github/fetch
    【解决方案4】:

    我还在浏览器和 nodejs 之间共享代码,并且还使用 JQuery 进行 Ajax 调用。 JQuery 需要一个我从 domino 使用的窗口。

    更新:

    if (typeof module !== 'undefined' && module.exports)
    {
      if (typeof global !== 'undefined' && typeof global.process !== 'undefined' &&
        Object.prototype.toString.call(global.process) === '[object process]') {
        var domino = require('domino');
        var window = domino.createWindow('<html></html>');
    
        var document = window.document;
        var $ = require('jquery')(window);
        var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
        $.support.cors = true; // cross domain, Cross-origin resource sharing
        $.ajaxSettings.xhr = function() {
          return new XMLHttpRequest();
        };
      }
    }
    

    【讨论】:

    • “huepi”为什么没有在任何地方定义?
    • 好点:)。我从使用它的项目中复制了它,它被称为 huepi:github.com/arndbrugman/huepi。我将从上面的代码中删除它。感谢您的注意!
    【解决方案5】:

    你可以使用Electron,它允许混合浏览器js和nodejs。

    之前尝试在nodejs中使用canvas2d,最后还是放弃了。 nodejs 默认不支持它,并且安装起来太难(很多很多......依赖)。 在我使用 Electron 之前,我可以轻松地使用我以前的所有 browserjs 代码,甚至是 WebGL,并将结果值(例如结果 base64 图像数据)传递给 nodejs 代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-15
      • 2011-11-08
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      相关资源
      最近更新 更多