Laravel:如何在重定向到任何网址时设置自定义标头

2022-01-11 00:00:00 header php laravel

我正在使用 Laravel 5.0 并尝试重定向到带有自定义标头的 url.但不知何故,我没有在重定向页面中获取标题值,或者我们可以说在重定向时没有发送标题值.

I am using Laravel 5.0 and trying to redirect to a url with custom headers. But somehow I am not getting the header value in redirected page or we can say header value is not getting sent while redirecting.

我正在使用此代码:

return redirect('http://www.anydomain.com')
            ->header('customvalue1', $customvalue1)
            ->header('customvalue2', $customvalue2);

如果我做错了什么,请告诉我.

Please let me know if I'm doing something wrong.

推荐答案

恐怕,其他答案完全错误且具有误导性.

I'm afraid, the other answer is completely wrong and misleading.

无论您使用什么语言或框架,都无法重定向到设置了自定义标题的页面.换句话说,没有办法触发 HTTP 重定向并导致客户端(浏览器)添加自定义标头.

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.

您可能认为这段代码应该可以正常工作:

You might be thinking that this code should work just fine:

return redirect('http://www.anydomain.com')
     ->header('customvalue1', $customvalue1)
     ->header('customvalue2', $customvalue2);

但它不会.您正在为指示浏览器重定向的响应设置自定义标头,而不是为重定向本身.

But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.

站点指示浏览器发出带有自定义标头的 HTTP 请求的唯一方法是使用 Javascript 和 XMLHttpRequest 对象.它需要在目标服务器上实现 CORS 以允许此类 ajax 请求.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.

请注意,页面不能设置 HTTP 请求标头,除非它使用 XMLHttpRequest 发出异步请求.这意味着您也不能在客户端使用自定义标头进行此类重定向.

Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.

这不是网络的运作方式.

That's not how the web works.

相关文章