您正在尝试从 Node.js 中创建 XHR。这是行不通的,因为 Node.js 只是一个 JavaScript 运行时,与浏览器不同。
如果您想通过 HTTP 协议从某处获取某些内容,您可以使用类似 request 的内容。例如(来自官方文档):
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
您可以查看this answer(也来自我),了解有关将 jQuery 与 Node.js 结合使用的更多信息。
UPDATE[d again!]:
所以您想知道 jQuery 节点模块如何区分浏览器和节点环境?当你在提供module 和module.exports 的CommonJS 或类似环境中require jQuery 时,你得到的是一个工厂而不是实际的jQuery 对象。如下所示,该工厂可用于创建 jQuery 对象,即使用 jsdom:
let jsdom = require("jsdom");
let $ = null;
jsdom.env(
"http://quaintous.com/2015/07/31/jquery-node-mystery/",
function (err, window) {
$ = require('jQuery')(window);
}
);
以下是 jQuery 区分浏览器和 io.js(或 Node.js)的方式:
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// implementation
return jQuery;
}));
我会使用 jQuery 的 npm 包用于 custom builds 而不是与 require 一起使用!
更新:
我觉得这个主题恰好让一些开发人员忙得不可开交,所以我结合了我自己的几个答案并写了an article关于整个 jQuery/Node 组合!