create-react-app调用Netlify Functions返回304错误及JSON解析异常求助
问题根因
两个报错是关联的:
SyntaxError: Unexpected token < in JSON at position 0说明你请求Netlify函数时,接口返回的不是预期的JSON,而是HTML内容(HTML以<开头,所以解析JSON时第一个字符就报错)- 304是浏览器缓存标识,本质是你的请求没有命中Netlify函数,Netlify直接返回了前端静态页面的缓存内容。
修复步骤
1. 修正netlify.toml配置
你当前配置的publish = "src"是错误的,publish必须指向前端构建后的产物目录,不能是源码目录:
[build] functions = "functions" publish = "build" # React项目默认构建产物在build目录,Vite项目改为dist
2. 确认函数文件路径正确
确保项目根目录下存在functions文件夹,fetch-weather.js直接放在该文件夹下,不要嵌套也不要放到src目录内,结构如下:
项目根目录 ├── functions/ │ └── fetch-weather.js ├── src/ ├── netlify.toml └── package.json
启动netlify dev时注意看控制台输出,出现Loaded function fetch-weather提示才说明函数被正常识别。
3. 优化函数返回头,避免解析和缓存问题
修改functions/fetch-weather.js,给返回值明确加响应头,指定返回格式为JSON,同时禁用缓存避免304问题:
const handler = async (event) => { try { const { city } = event.queryStringParameters; const API = process.env.REACT_APP_API_KEY; const response = await fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}` ); const data = await response.json(); return { statusCode: 200, // 新增响应头 headers: { "Content-Type": "application/json", "Cache-Control": "no-store, no-cache, must-revalidate" }, body: JSON.stringify(data), }; } catch (error) { // 错误分支也统一返回JSON格式 return { statusCode: 500, headers: { "Content-Type": "application/json", "Cache-Control": "no-store, no-cache, must-revalidate" }, body: JSON.stringify({ message: error.toString() }) }; } }; module.exports = { handler };
4. 检查环境变量配置
- 本地开发:在项目根目录新建
.env文件,填入你的OpenWeather API密钥:REACT_APP_API_KEY=你的实际API密钥 - 线上部署:需要在Netlify后台的「环境变量」板块添加同名变量,否则函数无法正常请求第三方接口。
5. 本地验证
重启netlify dev服务后,直接在浏览器访问http://localhost:8888/.netlify/functions/fetch-weather?city=beijing,确认返回的是正常的JSON格式天气数据,没有返回HTML内容。
内容的提问来源于stack exchange,提问作者user16589580
相关产品推荐
相关产品推荐

