【问题标题】:How to get redirect route from laravel redirectResponse?如何从 laravel redirectResponse 获取重定向路由?
【发布时间】:2020-11-02 09:55:50
【问题描述】:

所以我正在尝试测试我的 laravel 的中间件,该中间件将返回重定向。

如果请求不满足中间件的要求,请求将使用redirect()->route('name')重定向

我尝试像这样从中间件获取返回值

$response = $middleware->handle($request, function ($req) { return $req; }, 'server:summary:view:edit');
\Log::info($response);

$responseIlluminate\Http\RedirectResponse 的实例。 当我执行\Log::info($response); 时,我得到了这个结果。

HTTP/1.0 302 Found
Cache-Control: no-cache, private
Date:          Mon, 13 Jul 2020 08:12:27 GMT
Location:      https://myrandomurl.test/name

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='https://myrandomurl.test/name" />

        <title>Redirecting to https://myrandomurl.test/name</title>
    </head>
    <body>
        Redirecting to <a href="https://myrandomurl.test/name">https://myrandomurl.test/named</a>.
    </body>
</html>

那么如何从 Location 标签中获取 url 呢?或如何从 laravel redirectResponse 获取重定向 url?

我尝试浏览https://laravel.com/api/5.8/Illuminate/Http/RedirectResponse.html#method_content 的文档,但没有显示重定向路由的方法。

我需要路由来断言它以获得成功的测试结果。

【问题讨论】:

  • Location 是一个标题,那么$response-&gt;header('Location') 怎么样?
  • @apokryfos 没有用。 redirectResponse 上的 header() 方法用于设置请求标头。没有得到。
  • @apokryfos 不能使用$response-&gt;headers-&gt;get('Location'),因为redirectResponse 没有headers 属性。但是哦,你对assertRedirect() 说得对。我应该用那个。那么我可能应该删除这个问题。

标签: php laravel


【解决方案1】:

Illuminate\Http\RedirectResponse 继承了具有getTargetUrl 方法的Symfony\Component\HttpFoundation\RedirectResponse 类:

$response->getTargetUrl();

您可以改为使用assertRedirect 进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-28
    • 2013-07-19
    • 2019-10-05
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2020-03-24
    相关资源
    最近更新 更多