Laravel:如何在重定向到任何 url 时设置自定义标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36427106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: How to set custom header while redirecting to any url
提问by Anil Kumar Pandey
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.
我正在使用 Laravel 5.0 并尝试重定向到带有自定义标头的 url。但不知何故,我没有在重定向页面中获取标头值,或者我们可以说在重定向时没有发送标头值。
I am using this code:
我正在使用此代码:
return redirect('http://www.anydomain.com')
->header('customvalue1', $customvalue1)
->header('customvalue2', $customvalue2);
Please let me know if I'm doing something wrong.
如果我做错了什么,请告诉我。
回答by sepehr
I'm afraid, the other answer is completely wrong and misleading.
恐怕,另一个答案是完全错误且具有误导性的。
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.
无论您使用何种语言或框架,都不可能重定向到设置了自定义标头的页面。换句话说,无法触发 HTTP 重定向并导致客户端(浏览器)添加自定义标头。
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.
但不会。您正在为指示浏览器重定向的响应设置自定义标头,而不是为重定向本身设置。
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 请求的唯一方法是使用 Javascript 和XMLHttpRequest
对象。并且它需要在目标服务器上实现 CORS 以允许此类 ajax 请求。
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.
请注意,页面不能设置 HTTP 请求标头,除非它使用XMLHttpRequest
. 这意味着您也无法在客户端使用自定义标头进行此类重定向。
That's not how the web works.
这不是网络的运作方式。