cakephp 3.8.13处理未经授权的请求,并以JSON响应

问题描述

我已经在我的CakePHP应用程序中实现了https://github.com/ADmad/cakephp-jwt-auth。我的问题是,只要有未经授权的请求,它就会以HTML响应。

    <html>
        <head>
            <Meta charset="utf-8"/>
            <title>
            CakePHP: the rapid development PHP framework:
            Error   </title>
            <link href="/favicon.ico" type="image/x-icon" rel="icon"/>
            <link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
            <link rel="stylesheet" href="/css/cake.generic.css"/>
        </head>
        <body>
            <div id="container">
                <div id="header">
                    <h1>
                        <a href="https://cakePHP.org">CakePHP: the rapid development PHP framework</a>
                    </h1>
                </div>
                <div id="content">
                    <h2>Unauthorized</h2>
                    <p class="error">
                        <strong>Error: </strong>
                        An Internal Error Has Occurred.
                    </p>
                </div>
              </div>
          </body>
    </html>

但是根据本教程https://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/,它将使用JSON进行响应。教程中的示例响应是

{
    "success": false,"data": {
        "message": "You are not authorized to access that location.","url": "\/api\/cocktails.json","code": 401
    }
}

这是我的路由器

Router::prefix('api',function ($routes) {
    $routes->extensions(['json','xml']);
    Router::connect('/api/check',['_method' => 'GET','controller' => 'EmailNotification','action' => 'check','prefix' => 'api']);
    $routes->fallbacks('DashedRoute');
});

我该如何处理?我想要JSON中的未经授权的响应。谢谢。

解决方法

您可以尝试发送带有 Accept:application / json 标头的http请求