[工程架构思考-请求] http状态码-应用场景

62 阅读1分钟

Question

  1. 302 和 301在实际项目应用的区别?
  2. 链接的重定向与302, 301关系?
  3. 502 bad gateway
  4. 400 bad request
  5. 403 forbidden

Answer

  1. 502 bad gateway

    nginx开启了,但是反向代理的后端服务没有开启

  2. 400 bad request

    1. Django settings allow hosts 没有允许该IP的访问
    2. 常见于本地调试使用localhost:8000 访问后端服务器,但是后端服务允许的ip是127.0.0.1。这样后端接收到前端请求头中的host是localhost,返回400。这时候就需要将localhost:8000 换成127.0.0.1
  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
      
  4. 403

    1. 很常见的场景是NGINX没有权限访问文件/文件夹