我知道这是一个已经有答案的问题,但没有一个对我有效。由于某些原因,我不能使用:
$app->redirect($app->urlFor('home'));
或
$app->response->redirect($app->urlFor('home'));
路由"home"已定义,但出于某种原因,Slim只是返回了一个空的200响应。我做错什么了吗?
编辑:完整代码:
$app->get('/gensession', function() use ($app){
// set up session; this works
// if I echo anything here, it'll output on the page
$app->redirect('/'); // This doesn't work, neither does urlFor(<name>)
return;
});
这只会让我在/gensession上留下一页空白。Slim返回200(正常),其他都没有。没有错误。无输出。
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
编辑2:$app->响应的输出为:
object(Slim'Http'Response)#113 (5) { ["status":protected]=> int(302) ["headers"]=> object(Slim'Http'Headers)#115 (1) { ["data":protected]=> array(2) { ["Content-Type"]=> string(9) "text/html" ["Location"]=> string(1) "/" } } ["cookies"]=> object(Slim'Http'Cookies)#116 (2) { ["defaults":protected]=> array(6) { ["value"]=> string(0) "" ["domain"]=> NULL ["path"]=> NULL ["expires"]=> NULL ["secure"]=> bool(false) ["httponly"]=> bool(false) } ["data":protected]=> array(0) { } } ["body":protected]=> string(0) "" ["length":protected]=> int(0) }
注:["status":protected]=> int(302)
和["Location"]=> string(1) "/"
那么,如果响应对象明确包含这些属性,为什么不将它们返回给客户端呢?
问题可能是中间件。
我使用的是slim minimy(中间件),它显然写得不正确(据我所知)——
原始代码(片段):
public function __invoke(Request $request, Response $response,callable $next)
{
$next($request,$response);
$oldBody = $response->getBody();
$minifiedBodyContent = $this->minifyHTML((string)$oldBody);
$newBody = new Body(fopen('php://temp', 'r+'));
//write the minified html content to the new 'Slim'Http'Body instance
$newBody->write($minifiedBodyContent);
return $response->withBody($newBody);
}
注意$next($request,$response)
的使用。在Slim中,$response是不可变的(不能修改变量),因此必须用$next()
函数的返回值覆盖变量。
$response = $next($request,$response);
不是
$next($request,$response);
实际答案:
除了更改会话保存路径之外,我不知道我做了什么,但它现在可以工作了。我决定接受唯一的答案,因为它以后会对其他人有所帮助。非常感谢您的建议疯狂的红色
您应该像这样返回重定向:
$app->get('/gensession', function() use ($app){
return $app->redirect('/');
});