Aura Router AJAX Route Failure - Route Not Found - auraphp

To preface this question, I'm converting a demo application to utilize RESTful, SEO-friendly URLs; EVERY route with the exception of one of two routes used for AJAX requests works when being used in the application on the web, and ALL the routes have been completely tested using Postman - using a vanilla Nginx configuration.
That being said, here is the offending route definition(s) - the login being the defined route that's failing:
$routing_map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$routing_map->get('logout.read', '/services/authentication/logout', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'logout',
]
]
])->accepts([
'application/json',
]);
With Postman & xdebug tracing I think I'm seeing that it's (obviously) failing what I believe to be a REGEX check in the Path rule, but I can't quite make it out. It's frustrating to say the least. I looked everywhere I could using web searches before posting here - the Google group for Auraphp doesn't seem to get much traffic these days. It's probable I've done something incorrectly, so I figured it was time to ask the collective user community for some direction. Any and all constructive criticism is greatly welcomed and appreciated.
Thanx in advance, and apologies for wasting anyone's bandwidth on this question...

Let me make something clear. Aura.Router doesn't do the dispatching. It only matches the route. It doesn't handle how your routes are handled.
See the full working example ( In that example the handler is assumed as callable )
$callable = $route->handler;
$response = $callable($request);
In your case if you matched the request ( See matching request )
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
you will get the route, now you need to write appropriate ways how to handle the values from the $route->handler.
This is what I did after var_dump the $route->handler for the /signin route .
array (size=1)
'params' =>
array (size=1)
'values' =>
array (size=2)
'controller' => string '\Infraweb\LoginUI' (length=17)
'action' => string 'read' (length=4)
Full code tried below. As I mentioned before I don't know your route handling logic. So it is up to you to write things properly.
<?php
require __DIR__ . '/vendor/autoload.php';
use Aura\Router\RouterContainer;
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$map->get('application.signin.read', '/signin', [
'params' => [
'values' => [
'controller' => '\Infraweb\LoginUI',
'action' => 'read',
]
]
]);
$map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$matcher = $routerContainer->getMatcher();
// .. and try to match the request to a route.
$route = $matcher->match($request);
if (! $route) {
echo "No route found for the request.";
exit;
}
echo '<pre>';
var_dump($route->handler);
exit;
For the record, this is the composer.json
{
"require": {
"aura/router": "^3.1",
"zendframework/zend-diactoros": "^2.1"
}
}
and running via
php -S localhost:8000 index.php
and browsing http://localhost:8000/signin

Related

Data not posted for custom operation

I've got very big trouble with custom operations in Laravel backpack.
The documentated setup is clear but lack a real exemple with a form.
In my case I wanted to use the form engine to create a form for a relationship.
First step I did this :
public function getProtocoleForm($id)
{
// Config base
$this->crud->hasAccessOrFail('update');
$this->crud->setOperation('protocole');
//
$this->crud->addFields([
[ 'name' => 'codeCim',
'type' => 'text',
'label' => 'Code CIM',
],
]);
$this->crud->addSaveAction([
'name' => 'save_action_protocole',
'visible' => function($crud) {
return true;
},
'button_text' => 'Ajouter le procotole',
'redirect' => function($crud, $request, $itemId) {
return $crud->route;
},
]);
// get the info for that entry
$this->data['entry'] = $this->crud->getEntry($id);
$this->data['crud'] = $this->crud;
$this->data['saveAction'] = $this->crud->getSaveAction();
$this->data['title'] = 'Protocole ' . $this->crud->entity_name;
return view('vendor.backpack.crud.protocoleform', $this->data);
}
This is working fine, the form appears on the screen, then I did a setup for a post route like this :
Route::post($segment . '/{id}/protocolestore', [
'as' => $routeName . '.protocolestore',
'uses' => $controller . '#storeProtocole',
'operation' => 'protocole',
]);
The route appears correctly when I execute the artisan command but the storeProtocole function is never called. I checked the generated HTML and the form action is correct and checking in the "network" panel of the browser is also targeting the correct route.
Can you help me and tell me where I missed something ?
[Quick update] I made a mistake, the form route is not good in the HTML, it takes the route of the main controller.

datatype in request parameter $id = $this->params()->fromRoute('id');

so far I have worked only with integer values as request parameters in urls.
Now I need to work with strings which contain spaces etc. for example:
"xyz 666 888-VCT"
I send the route and parameters out of my view script:
PCB
I try to get it within my controller action:
$id = $this->params()->fromRoute('id');
How is the right way to catch a string value in this case?
edit:
here additional my routing paramters:
'pcb' => [
'type' => Segment::class,
'options' => [
'route' => '/pcb[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
'defaults' => [
'controller' => Controller\PcbController::class,
'action' => 'index',
],
],
],
I get always
the requested url could not match by routing
My url looks like follows:
...pcb/index/3441 99901 B 03 2519 xyz
I'm sure the problem are the spaces, so my question a bit more detailed, can I quote or somewhat the routing parameter?
SOLVED:
my regular expression in the routing was wrong, I changed it to:
'id' => '[a-zA-Z0-9\-\. /]*',

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',
],
],

Yii2 restful not working

By using this link I tried to have a restful app, but it's not working and always returned this:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please > > check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.4 (Win32) OpenSSL/1.0.1e PHP/5.5.1
I call it like this: localhost/restful/web/users
Edit:
This kind of call is not working either: localhost/restful/web/?r=users
It returned this:
Not Found (#404)
Page not found.
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you.
Have the same error (stil getting 404 Not found on each request) have solve it adding .htaccess to (my yii path)/web folder (the same where you have index.php):
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
This is because when you create an clean instance of Yii2 you don't have the .htaccess file (in my opinion probably the security reason).
for me the: (enabling curl and using it in my controller) installed via composer
composer require --prefer-dist linslin/yii2-curl "*"
use in controller
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use linslin\yii2\curl;//this was added
class UserController extends ActiveController
{
Don't work.
Maybe this helps someone :)
This is my config/web.php:
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager'=>[
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
And the controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController{
public $modelClass = 'app\models\User';
}
Also a created my model by gii.
The problem solved by enabling curl and using it in my controller.

Zend Router chaining problem with subdomain

I have a $siteRoute for subdomains:
$siteRoute = new Zend_Controller_Router_Route_Hostname(
':siteSlug.test.com',
array(
'module' => 'site',
),
array('siteSlug' => '^(programming|photography|gaming)$')
);
$router->addRoute('site', $siteRoute);
and i have $questionRoute for questions' fancy
$questionRoute = new Zend_Controller_Router_Route(
'questions/:questionId/:questionSlug',
array(
'controller' => 'question',
'action' => 'view',
'questionSlug' => ''
)
);
$router->addRoute('question', $siteRoute->chain($questionRoute));
all these two routes are matching without any problems. for example:
programming.test.com matches and dispatches for site route and programming.test.com/questions/132/test-headline matches for question route.
But when i assemble a new url with Zend_View's url helper or Zend_Router's assemble function for question route, it returns just the path, not domain like:
echo $questionRoute->assemble(array('questionId' => 1, 'questionSlug' => 'testing-testing', 'siteSlug' => 'programming'));
echoes questions/1/testing-testing not programming.test.com/questions/1/testing-testing.
How can i do this?
Try this piece of code, works fine for me (if u need more example tell me)
$router = Zend_Controller_Front::getInstance()->getRouter();
echo $router->assemble(array('questionId' => 1, 'questionSlug' => 'testing-testing', 'siteSlug' => 'programming'), 'question');
The router is only concerned about routing the path, i.e. take the path and match it to your modules, controllers and actions. It has basically no awareness of the domain. Assemble only creates the route (path) based on your arguments.
echo $_SERVER['HTTP_HOST'] . '/' . $questionRoute->assemble(...);