Reputation: 1
I'm using Phalcon\Mvc\Router
to map the routes and I have a GET route /api/test
like this,
$router = new \Phalcon\Mvc\Router(false);
$router->addGet('/api/test', [
'module' => 'api',
'controller' => 'test',
'action' => 'testapi',
]);
I'm able to make a GET request to this route and I'm able to get a 200 response, but if I make the method an invalid HTTP method and make a request (as below) it's also givinh me 200 response.
curl --location --request NOTHTPPMETHOD 'http://localhost/api/test'
I have tried changing addGet
to add
and passing the method
I have tried chaining the via
function in Phalcon\Mvc\Router
and passig ['GET']
Upvotes: 0
Views: 215
Reputation: 94
If I'm understanding your issue correctly, the default route is kicking in. When you create a new instance of Phalcon\Mvc\Router
, the default constructor argument is set to true
, which is the equivalent of doing $router->add('/:controller/:action/:params')
.
What you want to do is to pass the optional parameter as false
. That is to say, do $router = new Phalcon\Mvc\Router(false)
, then it won't add the default route.
Upvotes: 0
Reputation: 413
That's the expected behaviour. What your app is missing is to implement the notFound
method. Add to your router:
$router->notFound(
[
'controller' => 'index',
'action' => 'fourOhFour',
]
);
Or in a REST API:
$app->notFound(
function () use ($app) {
$app->response
->setStatusCode(404, 'Not found')
->setJsonContent([
'success' => false,
'msg' => 'Endpoint not found'
])
->send();
}
);
Another useful method is error
:
$app->error(
function ($exception) {
$this->response
->setStatusCode(503, 'Server unavailable')
->setContent('Error: ' . $exception->getMessage())
->send();
}
);
In this way your app can respond with custom messages and http status codes to failed requests.
Upvotes: 0