You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Google Trends API时出现“Unexpected token L in JSON at position 0”错误求助

Hey there, let's figure out why your Google Trends API code suddenly stopped working—since it ran fine before, here are the most likely fixes to test out:

1. Check for package or API endpoint changes

The google-trends-api npm package might have received an update that broke backward compatibility, or Google could have adjusted their underlying API endpoint. First, check what version you're using:

npm list google-trends-api

Run npm view google-trends-api changelog in your terminal to see if recent updates changed how parameters are handled. If you're on an older version, try updating to the latest:

npm install google-trends-api@latest

2. Fix date formatting (the "object-to-string parsing" clue)

Your current code passes Date objects directly to the API, but Google's endpoint might now require strict ISO 8601 string formatting instead of relying on the API to convert the Date object. Try converting your dates to ISO strings explicitly:

const googleTrends = require('google-trends-api');
googleTrends.relatedTopics({
  keyword: 'Chipotle',
  startTime: new Date('2015-01-01').toISOString(),
  endTime: new Date('2017-02-10').toISOString()
})
.then((res) => { console.log(res); })
.catch((err) => { console.log(err); });

This ensures the API gets a consistent string format instead of relying on how JavaScript serializes Date objects, which is probably where that parsing error is coming from.

3. Verify rate limits or authentication requirements

Google might have tightened up access to their Trends API—even if you didn't need an API key before, they could now require one. Check the package's README to see if authentication is now mandatory. If it is, generate an API key from Google Cloud Console and add it to your request:

googleTrends.relatedTopics({
  keyword: 'Chipotle',
  startTime: new Date('2015-01-01').toISOString(),
  endTime: new Date('2017-02-10').toISOString(),
  key: 'YOUR_GOOGLE_API_KEY'
})

Also, make sure you haven't hit rate limits—Google often caps how many requests you can make in a window, even without an API key.

4. Get detailed error info to narrow it down

Your current catch block only logs the generic error object. Modify it to print specific details that will tell you exactly what's breaking:

.catch((err) => { 
  console.log('Full error object:', err);
  console.log('Error message:', err.message);
  if (err.response) {
    console.log('API response status:', err.response.status);
    console.log('API response body:', err.response.body);
  }
});

This will show you if the error is from invalid parameters, a failed API request, or a parsing issue with the response.

Start with updating the package and adding detailed error logging—those two steps will usually point you straight to the problem.

内容的提问来源于stack exchange,提问作者NST

火山引擎 最新活动