32. http狀態碼 應用場景

哆啦A夢的前埠袋發表於2017-10-20

首發於我的GitHub部落格, 歡迎關注

Question

  1. 302 和 301在實際專案應用的區別?
  2. 連結的重定向與302, 301關係?
  3. 502 bad gateway
  4. 400 bad request

Answer

  1. 502 bad gateway

    nginx開啟了,但是反向代理的後端服務沒有開啟

  2. 400 bad request

    Django settings allow hosts 沒有允許該IP的訪問

  3. 302

    1. Django中的login_required中是使用了302跳轉來完成重定向操作

    2. login_required('/login') => user_passes_test => redirect_to_login => HttpResponseRedirect

    3. 之前疑惑為什麼後端可以使得前端頁面跳轉,後來明白了。瀏覽器在接收到302的status_code 之後,會自動跳轉到新的url

      # https://github.com/daoluan/decode-Django/blob/master/Django-1.5.1/django/http/response.py#L426
      class HttpResponseRedirectBase(HttpResponse):
          allowed_schemes = ['http', 'https', 'ftp']
      
          def __init__(self, redirect_to, *args, **kwargs):
              parsed = urlparse(redirect_to)
              if parsed.scheme and parsed.scheme not in self.allowed_schemes:
                  raise SuspiciousOperation("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
              super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
              # 關鍵部分,可以用來做連結重定向的檢測
              self['Location'] = iri_to_uri(redirect_to)
      
      
      class HttpResponseRedirect(HttpResponseRedirectBase):
          status_code = 302
      複製程式碼

相關文章