React Native中使用google-trends-api遇500错误求助
Hey there, let's break down why you're running into this 500 error and how to fix it. The core issue here is that google-trends-api is built specifically for Node.js environments—it relies on Node's core APIs like http, https, and filesystem modules that don't exist in React Native's JavaScript runtime (Hermes or JSC). When you try to require it in your RN app, the development server can't resolve those missing dependencies, hence the 500 error. Reinstalling the module won't help because this is an environment compatibility problem, not an installation issue.
Here's the solution: Use Google Trends' unofficial REST API directly
Instead of trying to use the Node.js module, you can fetch data directly from Google Trends' public API endpoints using React Native's built-in fetch or a library like axios. Here's a working example:
// Example function to fetch Google Trends data const getGoogleTrendsData = async () => { try { // Construct the request URL with your parameters const url = new URL('https://trends.google.com/trends/api/widgetdata/multiline'); // Add query parameters (customize these as needed) url.searchParams.append('hl', 'en-US'); // Language url.searchParams.append('tz', '360'); // Timezone offset (UTC-6) url.searchParams.append('req', JSON.stringify({ comparisonItem: [ { keyword: 'React Native', geo: '', time: 'today 12-m' } // Keyword, region, time range ], category: 0, // 0 = All categories property: '' })); // Send the request with a valid User-Agent (Google blocks default RN fetch agents) const response = await fetch(url.toString(), { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } }); // Clean up the response: Google adds a prefix ")]}'\n" to prevent JSON hijacking const rawText = await response.text(); const cleanedText = rawText.replace(/^\)]}'\n/, ''); const trendsData = JSON.parse(cleanedText); console.log('Successfully fetched trends:', trendsData); return trendsData; } catch (error) { console.error('Error fetching Google Trends:', error); } };
Key notes to keep in mind:
- User-Agent is mandatory: Google will block requests without a desktop-like User-Agent string. Update the value if you run into 403 errors.
- Response cleanup: The raw response starts with
)]}'\n—you must remove this before parsing JSON, otherwise you'll get a syntax error. - Unofficial API caveat: This isn't a documented Google API, so endpoints or response formats might change without warning. For production apps, consider using a third-party service that provides stable Google Trends data via a proper API.
内容的提问来源于stack exchange,提问作者himori123

