【问题标题】:Laravel sending status codes with redirectLaravel 通过重定向发送状态码
【发布时间】:2022-11-05 22:28:29
【问题描述】:

如果刀片中的'是一个代码

@inject('response', \Illuminate\Http\Response::class)
{{ $response->status() }} //it displays always only 200 instead of 302 or 400
<form>..login form..</form>

在控制器中

//view:
public function showLoginForm()
{
    return view('auth.login');
}

//submit
public function customLogin(Request $request)
{
    $request->validate([
        'email' => 'required|string',
        'password' => 'required|string',
    ]);
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        return redirect()->route('index')->withSuccess('Login success');
    }
    //status code 400 not work
    return redirect(null,400)->route('login')->withDanger('Wrong password or email');
}

我想要重定向(不是响应)。我正在寻找适用于浏览器和测试的解决方案,例如 C:\xampp\htdocs\projectname\tests\Feature\LoginTest.php

public function testSuperAdmin() {
    $response = $this->post('/login', [
        'email' => 'yy@blaa.com',
        'password' => '123',
    ]);
    $response->assertStatus(400);
}

【问题讨论】:

    标签: laravel testing status


    【解决方案1】:

    TLDR:你不能这样做,因为 HTTP 不允许这样做。


    长答案:互联网上有通信标准。 Web 服务器(Nginx、LiteSpeed、Apache 等)和浏览器(Chrome、Firefox、Opera 等)必须遵守这些标准才能正常工作。这些标准之一是由 Internet 工程任务组 (IETF) 制定的标准 HTTP。

    您可以从here (archive) 访问 IETF 的 HTTP 规范。如果您查看其中的“10.2.2. Location”subtitle,您会发现基于 HTTP 标头的重定向仅适用于 201 和 3xx 状态代码。

    来自vendor/symfony/http-foundation/RedirectResponse.php(Laravel 使用)的示例代码:

    class RedirectResponse extends Response
    {
    
        public function __construct(string $url, int $status = 302, array $headers = [])
        {
    
            // ...
    
            if (!$this->isRedirect()) {
                throw new InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status));
            }
    
            // ...
        }
    
        public function isRedirect(string $location = null): bool
        {
            return in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location'));
        }
    
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-10-14
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多