如何为转发的请求设置标头

时间:2015-09-30 15:09:49

标签: http-headers laravel-5

我的控制器的方法需要设置标题,例如X-Authorization。创建新对象(store操作)后,我执行转发以显示新创建的对象(show操作):

$request = Request::create(route('api.v1.b.show', ['booking' => 4]), 'GET');
Request::replace($request->input());
return Route::dispatch($request);

如果我禁用授权检查,转发工作正常,但否则失败。即。标题已经消失了。我想将Request::header('X-Authorization')带来的请求标头复制到转发的请求中。有可能吗?

我尝试$request->header('X-Authorization', 'xxxxx')没有成功。在发送之前还尝试了PHP的header()并且无效。

有什么想法吗?干杯

3 个答案:

答案 0 :(得分:8)

好的,我认为您需要像这样设置标题:

$request = Request::create(route('api.v1.b.show', ['booking' => 4]), 'GET');
$request->headers->set('X-Authorization', 'xxxxx');

这是你问题的答案。

我的问题是:我们在哪里可以为每个api请求设置此标头(转发)?因为我个人有5个标题要设置请求,我不想重复自己。

答案 1 :(得分:0)

万一有人需要,我只想发布它可以帮助某人

       $request =new Request();
       $request->headers->set('Authorization', {{your_key_here}});

答案 2 :(得分:0)

// From @musicvicious answer
$request = Request::create(route('api.v1.b.show', ['booking' => 4]), 'GET');

如果您想一次设置多个标题,则可以将更多参数传递给Request::create()

/**
 * Creates a Request based on a given URI and configuration.
 *
 * The information contained in the URI always take precedence
 * over the other information (server and parameters).
 *
 * @param string $uri        The URI
 * @param string $method     The HTTP method
 * @param array  $parameters The query (GET) or request (POST) parameters
 * @param array  $cookies    The request cookies ($_COOKIE)
 * @param array  $files      The request files ($_FILES)
 * @param array  $server     The server parameters ($_SERVER)
 * @param string $content    The raw body data
 *
 * @return static
 */

$server参数中传递以“ HTTP_”开头的标头。

$server = [
    'HTTP_YOUR_HEADER_NAME_1' => 'Value 1',
    'HTTP_YOUR_HEADER_NAME_2' => 'Value 2',
];

您的请求将具有以下标题

your-header-name-1: Value 1;
your-header-name-2: Value 2;
相关问题