Cannot call a Craft 3 module's action

602 views Asked by At

I'm trying to setup a controller action that can be called by a cron job. I have a controller living inside modules/chill/controllers/NotificationController with the action actionIndex running in Homestead at http://chill.test.

When calling the url http://chill.test/actions/chill/notifications/index I get a native browser login screen. The controller extends craft\web\Controller and overrides $allowAnonymous.

The controller looks like this:

<?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';
    }
}

Also calling the url via Paw with application/json setup in the headers I get the following 401-response:

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

Any ideas on how to bypass the login popup or am I setting this up wrong?

1

There are 1 answers

0
mylesthe.dev On

I normally setup a Module and then register routes using 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',
                 ],
             ];
         }
     );
}