【发布时间】:2012-01-28 03:46:30
【问题描述】:
是否可以在 node.js 中完全按照语法方式使用 jQuery.ajax()?
我正在尝试与 node.js 共享非 UI 浏览器代码。我不想用我自己的包装器替换所有现有的函数调用。
目前,当我尝试它时,默认情况下会显示“无传输”,因为 jQuery 会进行域检测。如果我通过设置jQuery.support.cors 将其关闭,它会说 XMLHttpRequest.open() 不可用。
【问题讨论】:
是否可以在 node.js 中完全按照语法方式使用 jQuery.ajax()?
我正在尝试与 node.js 共享非 UI 浏览器代码。我不想用我自己的包装器替换所有现有的函数调用。
目前,当我尝试它时,默认情况下会显示“无传输”,因为 jQuery 会进行域检测。如果我通过设置jQuery.support.cors 将其关闭,它会说 XMLHttpRequest.open() 不可用。
【问题讨论】:
如果您想要确切的 jQuery.ajax 语法,请尝试 https://github.com/driverdan/node-XMLHttpRequest
但如果你真的可以控制你调用 ajax 的目的,你应该使用 node 的 http.request 或像 request 这样的模块
【讨论】:
XMLHttpRequest 函数,如下所示:github.com/tmpvar/jsdom/issues/380
我能够使用 XMLHttpRequest 模块解决“无传输”问题,如下所示:
var $ = require('jquery'),
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function() {
return new XMLHttpRequest();
};
【讨论】:
还可以考虑 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...
【讨论】:
djax 不支持相当方便的 complete 处理程序,所以我决定使用未来技术:github.com/github/fetch
我还在浏览器和 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();
};
}
}
【讨论】:
你可以使用Electron,它允许混合浏览器js和nodejs。
之前尝试在nodejs中使用canvas2d,最后还是放弃了。 nodejs 默认不支持它,并且安装起来太难(很多很多......依赖)。 在我使用 Electron 之前,我可以轻松地使用我以前的所有 browserjs 代码,甚至是 WebGL,并将结果值(例如结果 base64 图像数据)传递给 nodejs 代码。
【讨论】: