urlManager can't find site/index in Yii2 - rest

I just create a Basic App schema in Yii 2.
I try to test RESTFull api.
The site is working, by default, but when I change the urlManager
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'cliente'],
],
],
I only get 404 error.
I lost site/index!!!
Any idea?

It is this setting:
'enableStrictParsing' => true,
Look here:
https://github.com/yiisoft/yii2/blob/master/framework/web/UrlManager.php#L323
There are no explicit url rules for the siteController defined.
Read more here:
https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing#url-rules

site/index action no longer works because of this setting: 'enableStrictParsing' => true. From $enableStrictParsing documentation:
If strict parsing is enabled, the incoming requested URL must match at least one of the $rules in order to be treated as a valid request. Otherwise, the path info part of the request will be treated as the requested route.
So if you enable this setting, you need to have matching URL rule to support given URL. In your case, you have only one rule for REST endpoint, so any other URL will not work. You should either disable this setting or add rule for your main page:
'rules' => [
'' => 'site/index',
['class' => 'yii\rest\UrlRule', 'controller' => 'cliente'],
],

Related

OPTION verb is not working for a list of all records in Yii 2 app

I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for OPTIONS /users:
When I execute OPTIONS /user/20 then I am getting:
200 OK
Empty content
List of allowed methods
But, when I execute OPTIONS users then I am getting 405 Method not Allowed.
What can be wrong or what am I missing?
You are getting 405 Method Not Allowed not because of routing but because of yii\filters\VerbFilter.
The yii\rest\Controller uses verbs() method to set up VerbFilter.
The yii\rest\ActiveController overrides verbs() method and sets VerbFilter to only allow GET and HEAD requests for index action.
It uses options action for OPTIONS method.
If you really want to use index action for OPTIONS method. You have to override verbs() method yourself and add OPTIONS as allowed method for that action. For example like this:
protected function verbs()
{
$verbs = parent::verbs();
$verbs['index'][] = 'OPTIONS';
return $verbs;
}
Or if you want to use options action you have to modify patterns settings as suggested by #Bizley in comments.

Yii2: How to add separate api module in root directory?

I have yii2 basic project with working web application functionality and now i want to add api functionality for this application.Currently i have directory stucture as
root
+ api
+ config
+ modules
+ v1
+ controllers
+.htaccess
+index.php
+index.php
+.htaccess
+ web
+ config
+ controllers
...
Now i am requesting /api/v1/controller/action but is getting 404 not found as response. Anything i have to configure?
If you have set up everything correctly and added the new api alias in the common/bootstrap.php file like Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');, you need to define the rules under urlManager in order to access the specific controller action inside your api/config/main.php.
For example I have a controller inside the api/modules/v1/controller/ with the name Lead and have two actions with the name actionTest() and actionLists() and i want to be able to send POST request to the actionLists() and GET request to the actionTest() then i will define them in the UrlManager like below
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'pluralize' => false,
'controller' => 'v1/lead',
'tokens' => [
'{id}' => '<id:\\w+>'
],
'extraPatterns' => [
'POST create' => 'create',
'GET test' => 'test'
]
],
]
]
Now I can send POST request to http://example.com/api/v1/lead/list and GET request to http://example.com/api/v1/lead/test?id=1234
Note: Notice the 'pluralize'=>false for the rule if no set you will notice the controller ID lead appears in plural form as leads in the endpoint URLs. This is because yii\rest\UrlRule automatically pluralizes controller IDs when creating child URL rules. You may disable this behavior by setting yii\rest\UrlRule::$pluralize to be false.

URL-Manager will not route

I cloned our repositorie and created excatly the same URL-rules like at my own project. Now, i will get error like this after having logged in:
Firefox:
Fehler: Umleitungsfehler
The website called is rerouting request,which never will come to an end.
This problem sometimes occures, if cookies are deactivated
Chrome:
ERR_TOO_MANY_REDIRECTS
I definetly accepted using cookies at both browser!!
Debugging shows me,that I have dozen of 302-Requests,so Yii breaks down!
I use Windows, not LINUX, so I don't care about any permissions.
Here are the rules:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'/' => 'site/login',
'home' => 'site/index',
'logout' => 'site/logout',
'contact' => 'site/contact',
'signup' => 'site/signup',
'reset' => 'site/request-password-reset',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<action:(contact|captcha)>' => 'site/<action>'
],
Here is frontend configuration:
<?php
$config = [
// LZA 17-07-30
'sourceLanguage' => 'de-DE',
'language' => 'de-DE',
// LZA 17-07-30 siehe Funktionen in http://demos.krajee.com/grid#module
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '4lD2RxDNkC4ckpwxTmkDzOLIvk0JMs3F',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// LZA 17-07-30 CRUD
'generators' => [// customized CRUD generator
'crud' => [
// 'class' => 'app\myCrud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'class' => '\common\wsl_dev\wsl_crud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'templates' => [
'myCrud' => '/#common/wsl_dev/wsl_crud/crud/default', //LZA 17-07-20 Templatename und Templatepfad
]
]
],
// LZA 17-07-30 CRUD
];
}
return $config;
If I deacitvate URLManger,setting
'enablePrettyUrl' => false,
everything works fine.
If I put in manually Url like this:
http://localhost/yii2_perswitch/frontend/web/yiic.php/home
everything works fine,too
Any ideas,how to fix this?
I deleted all my cookies,without any effects!
Solution 1:
Enable debug mode from web/index.php (uncomment these two lines):
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
and you can see exactly what causes the problem.
Redirected too many times error was because the 777 permissions for
runtime and assets folder were not set.
Solution 2:
I think that the problem is related with the path or domain of the cookie. I believe that this info could be useful.
https://github.com/samdark/yii2-cookbook/blob/master/book/cookies.md

Hide controller and action in pretty URL with Yii2

I need to change a URL in Yii2 using the URL Manager from
http://www.domain.com/index.php?r=tamil-article/articles&categ=Innovation&id=44
to
http://www.domain.com/44/Innovation.html
How can this be done?
You can resolve this by configuring your UrlManager to use prettyUrls.
After that you can add a custom url rule to the rules array (in config/main.php):
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Add the .html suffix
'suffix' => '.html',
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => [
'<id:\d+>/<categ:\w+>' => 'tamil-article/articles',
],
],

Yii2 REST ful Api how to send status code

Yii2 Restful API
In the above link they mention for GET Search method , Please anyone tell me for like POST create and PUT Update ...
In main.config under rules i created like,
['class' => 'yii\rest\UrlRule', 'controller' => 'v1/lkup-access-profile','extraPatterns' => ['POST create' => 'create']],
But its comes error as Method Not Allowed. This url can only handle the following request methods: POST.
yii\rest\UrlRule will create default REST URLs and actions. There's no need to add 'extraPatterns' => ['POST create' => 'create']. It's already built in. Check out the docs http://www.yiiframework.com/doc-2.0/yii-rest-urlrule.html
Use extraPatterns to extend default routes for controller. For example
['class' => 'yii\rest\UrlRule', 'controller' => 'v1/invite',
'extraPatterns' => [
'PUT {id}/accept' => 'accept',
'PUT {id}/reject' => 'reject',
],
],