Laravel Pjax 總是 abort(422)
使用spatie/laravel-pjax
的時候遇到總是abort(422)
的情況,查了一圈大多說原因是渲染的頁面裡找不到監聽的 pjax container。
可檢查過後我的頁面裡都是有id="pjax-container"
的,請求頭裡也有X-PJAX-CONTAINER: #pjax-container
。
查原始碼加除錯輸出找到問題的原因:
spatie/laravel-pjax
裡使用了Symfony\Component\DomCrawler\Crawler
來檢查渲染的 DOM 中是否存在指定的X-PJAX-CONTAINER
。
// Middleware/FilterIfPjax.php protected function filterResponse(Response $response, $container) { $crawler = $this->getCrawler($response); $response->setContent( $this->makeTitle($crawler). $this->fetchContainer($crawler, $container) ); return $this; }
abort(422)
發生在fetchContainer()
中:
protected function fetchContainer(Crawler $crawler, $container) { $content = $crawler->filter($container); if (!$content->count()) { abort(422); } return $content->html(); }
注意到在filterResponse()
中是把當前的$response
傳給了$crawler
的,那麼如果當前的$response
其實是個錯誤頁面呢?這裡就會發生找不到#pjax-container
的情況了。
輸出一看果然,$response
是個異常資訊頁面。我遇到的問題是忘了migrate
。