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

Django项目部署Heroku后fetch GET请求开发正常生产环境报错求助

根因定位

  1. 核心问题来自Sentry上报的错误:Heroku生产环境的服务器无法成功连接www.wordreference.com,getaddrinfo failed属于DNS解析失败,说明Heroku运行节点无法解析该域名的IP地址,导致你的WordReference翻译请求直接超时抛出异常。
  2. 前端的JSON解析报错是衍生问题:后端抛出未捕获的异常后,Django默认返回HTML格式的500错误页面,内容开头为<,你直接调用response.json()解析非JSON格式的HTML内容自然会报错。

修复步骤

第一步:后端加异常捕获,统一返回JSON格式

修改views.py代码,避免异常时返回HTML错误页:

import requests
from django.http import JsonResponse

def translate_word(request, word):
    try:
        wr = WordReference('es', 'en')
        wr_obj = wr.translate(word)
        entries = wr_obj['translations'][0]['entries']
        twlist = []
        for entry in entries:
            for dict in entry['to_word']:
                if dict['meaning'] not in twlist:
                    twlist.append(dict['meaning'])
        return JsonResponse({"twlist": twlist, "code": 0}, safe=False)
    except (requests.exceptions.ConnectionError, KeyError, Exception) as e:
        # 异常时也返回标准JSON结构
        return JsonResponse({"twlist": [], "code": 1, "msg": "翻译服务暂时不可用"}, status=500)

第二步:前端加错误捕获,避免未处理的Promise异常

修改demo.js代码,增加接口错误处理逻辑:

translate: (word) => {
  fetch(`/translate/${word}`, {
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'X-Requested-With': 'XMLHttpRequest', //适配request.is_ajax()
  },
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('接口请求失败')
    }
    return response.json()
  })
  .then(data => {
    // 原有数据渲染逻辑
  })
  .catch(err => {
    // 错误提示逻辑,可给用户展示翻译失败提示
    console.error('翻译出错:', err)
  })
},

第三步:解决Heroku无法访问WordReference的问题

  • 先登录Heroku后台进入应用的在线终端,执行curl https://www.wordreference.com测试连通性
  • 若确认连通失败,大概率是Heroku动态出口IP被WordReference反爬屏蔽,可更换为其他支持无限制公网访问的翻译接口,或配置Heroku代理插件解决访问限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:39:04