在中间件中设置标题 [英] set header in middleware
本文介绍了在中间件中设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在中间件中设置标头,以避免Google漫游器将诸如登录页面之类的内容编入索引.我实际上使它起作用,但是遇到了我无法理解的错误.
I tried to set a header in a middleware to avoid Google bot for indexing something like a login page. And I actually made it work but came across this error which I cannot understand.
public function handle($request, Closure $next)
{
$next($request)->header('x-robots-tag', 'none', false);
return $next($request);
}
上面的代码不会在下面的代码中添加此标头x-robots-tag: none
.
The code above won't add this header x-robots-tag: none
while the below code does.
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('x-robots-tag', 'none', false);
return $response;
}
基本上不是同一回事吗?唯一的区别是将$next($request)
放入变量还是不放入变量.为什么会这样?
Isn't it basically the same thing? The only difference is putting $next($request)
in a variable or not. Why is this?
推荐答案
让我们逐步了解第二个版本:
Let's walk through the second version:
public function handle($request, Closure $next)
{
$response = $next($request); //You get the Response instance and store it
$response->header('x-robots-tag', 'none', false); //you set the header
return $response; //and then you return it
}
而
public function handle($request, Closure $next)
{
$next($request)->header('x-robots-tag', 'none', false);//You set the header to the response
return $next($request);// Here you get another instance thus the previous result is lost
}
想象一下$next($request)
的行为就像一个工厂.
Imagine that $next($request)
behaves like a factory.
这篇关于在中间件中设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文