如何为转发请求设置headers

How to set headers for forwarded request

我的控制器方法需要设置 header,例如X-Authorization。创建新的 object 后(store 操作),我做一个转发以显示新创建的 object(show 操作):

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

如果我禁用授权检查转发工作正常,否则转发失败。 IE。 header 已经消失了。我想将请求 header 复制到转发的请求中,我可以通过 Request::header('X-Authorization') 获得它。可能吗?

我试过 $request->header('X-Authorization', 'xxxxx') 但没有成功。在发货前也尝试了 PHP 的 header(),但没有用。

有什么想法吗?干杯

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

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

这就是你问题的答案。

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

如果有人可能需要这个,我只是想 post 它可以帮助某人

       $request =new Request();
       $request->headers->set('Authorization', {{your_key_here}});
// From @musicvicious answer
$request = Request::create(route('api.v1.b.show', ['booking' => 4]), 'GET');

如果你想一次设置多个header,你可以传递更多的参数给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_' 开头的 header。

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

您的请求将 header 如下所示

your-header-name-1: Value 1;
your-header-name-2: Value 2;