You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中使用$.getJSON获取JSON数据报错:$未定义的解决方法

解决Node.js中$ is not defined的问题

嗨,作为Node.js新手碰到这个问题太正常了——毕竟jQuery本来就是为浏览器环境设计的,直接在Node里用肯定会出问题!咱们一步步来搞定它:

为什么会报错?

在浏览器里,jQuery会自动把$挂载到全局的window对象上,但Node.js没有window这个浏览器专属的环境对象,就算你通过npm装了jQuery,它也没法自动初始化出可用的$变量,所以就抛出了ReferenceError。

推荐方案:放弃jQuery,用Node专属的HTTP请求库

其实在Node.js里完全没必要用jQuery来发请求,有很多更轻量、更适配Node环境的库,比如node-fetch(和浏览器的Fetch API用法几乎一致)或者axios。这里用node-fetch举例子,正好还能把你之前注释的Promise代码用上:

  1. 先安装依赖:
npm install node-fetch
  1. 修改你的模块代码:
const fetch = require('node-fetch');

module.exports = {
  getTextWeatherUsingStation: function(theStation) {
    const theURL = `https://api.weather.gov/stations/${theStation}/observations/current`;
    return new Promise((resolve, reject) => {
      fetch(theURL)
        .then(response => {
          // 先检查请求是否成功
          if (!response.ok) {
            throw new Error(`请求失败,状态码:${response.status}`);
          }
          return response.json(); // 直接解析JSON数据
        })
        .then(data => {
          const myJSON = JSON.stringify(data);
          // 这里可以根据你的需求处理数据,然后返回结果
          resolve(myJSON);
        })
        .catch(error => {
          // 捕获请求或解析过程中的错误
          reject(error);
        });
    });
  }
};

这样修改后,你的函数就能正常返回Promise,调用方也能通过.then()或者async/await来处理结果,完全符合Node.js的异步编程风格。

如果你非要用jQuery(不推荐)

要是你坚持想用jQuery的$.getJSON,那得先模拟出浏览器的环境,需要用到jsdom来创建一个虚拟的window对象:

  1. 安装依赖:
npm install jquery jsdom
  1. 修改代码初始化jQuery:
const { JSDOM } = require('jsdom');
const { window } = new JSDOM();
// 把jQuery绑定到虚拟的window对象上,这样才能得到可用的$
const $ = require('jquery')(window);

module.exports = {
  getTextWeatherUsingStation: function(theStation) {
    const theURL = `https://api.weather.gov/stations/${theStation}/observations/current`;
    return new Promise((resolve, reject) => {
      $.getJSON(theURL, function(data) {
        const myJSON = JSON.stringify(data);
        resolve(myJSON);
      })
      .fail(function(error) {
        // 捕获请求失败的情况
        reject(error);
      });
    });
  }
};

不过还是要提醒你,这种方式需要额外模拟浏览器环境,会增加不必要的开销,在Node.js里用专门的HTTP请求库才是更合理的选择。

内容的提问来源于stack exchange,提问作者Earth 2 Eddie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:47:30