在Node.js中运行jQuery遇报错,已尝试多方案,拟更换JSON数据获取方式
Hey there! Let's break this down first—your jQuery import issue in Node.js isn't about your code itself, it's about how jQuery was built. jQuery is designed for browser environments where a native window and DOM exist, so just requiring it directly in Node won't work unless you simulate that browser context with jsdom.
Quick Fix for jQuery (if you ever need it later)
If you wanted to get jQuery working with jsdom, here's the correct setup:
const { JSDOM } = require('jsdom'); // Create a simulated browser window const dom = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(dom.window);
This gives jQuery the window object it needs to initialize properly—your earlier empty results probably came from not binding jQuery to the jsdom window correctly.
But since you don't need jQuery, here are better ways to fetch JSON in Node.js
You’ve got solid, lightweight options tailored for Node.js environments:
1. Use Node.js's built-in fetch (Node 18+)
Node.js 18 and above includes the browser-standard fetch API by default, no extra installs needed:
async function fetchJsonData() { try { const response = await fetch('https://your-api-url.com/data.json'); // Verify the request succeeded if (!response.ok) { throw new Error(`Request failed with status: ${response.status}`); } const jsonData = await response.json(); console.log('Fetched JSON:', jsonData); } catch (error) { console.error('Error fetching JSON:', error.message); } } // Run the function fetchJsonData();
2. Use the native https module (for older Node versions)
If you’re on a Node version before 18, the built-in https module is always available:
const https = require('https'); https.get('https://your-api-url.com/data.json', (response) => { let rawData = ''; // Collect data chunks as they arrive response.on('data', (chunk) => { rawData += chunk; }); // Parse JSON once the response finishes response.on('end', () => { try { const parsedData = JSON.parse(rawData); console.log('Parsed JSON:', parsedData); } catch (error) { console.error('Error parsing JSON:', error.message); } }); }).on('error', (error) => { console.error('Request error:', error.message); });
3. Use a lightweight third-party library like axios
If you prefer a simpler API with built-in JSON handling, axios is a great choice. First install it:
npm install axios --save
Then use it in your code:
const axios = require('axios'); async function getJsonWithAxios() { try { const response = await axios.get('https://your-api-url.com/data.json'); console.log('Axios fetched JSON:', response.data); } catch (error) { console.error('Axios error:', error.message); } } getJsonWithAxios();
All these methods avoid the overhead of jQuery when you only need to fetch JSON data.
内容的提问来源于stack exchange,提问作者Karim Shoorbajee

