【问题标题】:It is possible to get backend custom error message with d3.json?可以使用 d3.json 获取后端自定义错误消息吗?
【发布时间】:2019-08-22 09:07:02
【问题描述】:

我开发了一个 django 应用程序,其中有一个 d3js 交互式树。我使用 d3.json 从 django 视图中获取树数据。我创建了一个装饰器来检查用户是否已登录以允许该请求。当用户登录时我没有问题,但是当装饰器返回带有重定向 url 的 jsonResponse 时,我只有带有状态描述的状态错误。

我阅读了 d3js 和 promise 文档,但我没有找到一个答案来返回带有我的自定义响应的 jsonresponse。

d3.json(d.data.url).then(function(data) {
          // process data no problem
        }, function(error){
          console.log(error);
        });
def check_user_permission_js(view_function):
    @wraps(view_function)
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view_function(request, *args, **kwargs)
        messages.warning(request,
            "Your account doesn't have access to this page "
            + "or your session has expired. "
            + "To proceed, please login with an account that has access.")
        return JsonResponse({'not_authenticated': True,
                             'redirect_url': settings.LOGIN_URL,'data':[]}, status=500)
    return wrapper

【问题讨论】:

    标签: django d3.js promise


    【解决方案1】:

    我认为这个问题并不特定于 d3 或前端代码。

    如果您使用的是 d3 v5,d3.json 是浏览器 fetch API documented here 的薄包装,它似乎正确地返回了非 200 状态代码。如果问题是您没有让JsonResponse 中提供的自定义字段出现在返回到前端的响应中,那么问题与Django JsonResponse 方法的使用有关,它不是使用不同的数据获取库会发生变化。

    【讨论】:

      【解决方案2】:

      我不认为错误来自 django,因为我已经将 JSONresponse 与 ajax 请求一起使用,效果很好。示例:

      $.ajax({
                url: "/browser/project/get-header",
                type: "POST",
                success: function(data) {
                  // process my data
                },
                error: function(jqXHR){
                  if (jqXHR.responseJSON.message){
                    writeMessages(jqXHR.responseJSON.message, 'error');
                  }
                  else{
                    writeMessages(
                      'An error occur: the sample list can not be loaded!',
                      'error');
                  }
                }
              });
      

      我的问题与 fetch 以及 d3js 如何使用 d3.json 返回错误有关。

      为了暂时解决我的问题,我使用上述请求,但最后我只想使用 D3JS 的功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2016-12-30
        • 2016-01-15
        • 1970-01-01
        • 2015-12-07
        • 2018-05-23
        相关资源
        最近更新 更多