问题
I've recently built a small API using the Slim PHP framework and it is working great. I would however like to set a GET route for the root "/" which responds with a basic message and have any other GET requests return an "access denied".
Upon reading both the documentation and various examples, I have not been able to figure out how to accomplish either of these tasks. My project only relies on POST routes but being able to respond to GET requests aimed at both the root domain and any other pages would be fantastic.
Code:
// SLIM INSTANCE
$app = new \Slim\Slim();
$app->contentType('application/json');
// SLIM ROUTES
$app->group('/core', function() use ($app)
{
$app->post( '/create', 'Create' );
$app->post( '/start', 'Start' );
$app->post( '/stop', 'Stop' );
$app->post( '/delete', 'Delete' );
});
回答1:
if you want to respond to different methods, just use the map()
-Method:
$app->map('/create', 'Create')->via('GET', 'POST');
To register a 'default route', which will always reply with 'access denied' if no route matched, you can override the 'notFound'-Handler:
$app->notFound(function () use ($app) {
$app->response->setStatus(403);
//output 'access denied', redirect to login page or whatever you want to do.
});
To accomplish a 'root'-route: $app->get('/',function(){/*...*/});
should to exactly this.
来源:https://stackoverflow.com/questions/32568765/default-get-route-with-slim-php