首页 > 解决方案 > 无法调用工艺 3 模块的操作

问题描述

我正在尝试设置一个可以由 cron 作业调用的控制器操作。我有一个控制器住在里面modules/chill/controllers/NotificationController,动作actionIndex在 Homestead 中运行http://chill.test

调用 url 时,http://chill.test/actions/chill/notifications/index我得到一个本机浏览器登录屏幕。控制器扩展craft\web\Controller并覆盖 $allowAnonymous。

控制器如下所示:

<?php
namespace Chill\Controllers;

use Craft;
use craft\web\Controller;

class NotificationsController extends Controller
{
    protected $allowAnonymous = true;

    /*
     * Call via: http://chill.test/actions/chill/notifications/index
     */
    public function actionIndex(){

        Craft::$app->getDeprecator()->log("Chill", "Testing the error logging on index action", 'notifications.log');

        return 'Welcome to the NotificationsController actionIndex() method';
    }
}

还通过 Paw 在标题中使用 application/json 设置调用 url,我得到以下 401 响应:

{
  "error": "Your request was made with invalid credentials."
}

关于如何绕过登录弹出窗口的任何想法还是我设置错误?

标签: phpmodulecontrollerhomesteadcraftcms

解决方案


我通常设置一个模块,然后使用 Crafts Events 注册路线

private function _registerSiteRoutes()
{
     Event::on(UrlManager::class, UrlManager::EVENT_REGISTER_SITE_URL_RULES,
         function (RegisterUrlRulesEvent $event) {
             $event->rules[] = [
                 'class' => 'yii\rest\UrlRule',
                 'controller' => ['api/' => 'my-module/api/v1/base'],
                 'extraPatterns' => [
                      'GET notifications' => 'notifications',
                 ],
             ];
         }
     );
}

推荐阅读