The small REST API I made works locally well. When transferring on a server the GET requests all work, but the POST don't.
I have read many people have this effect and the problem most of the time is wrong routing.
Looks like the trailing slash creates a redirect which causes the problem. Without the trailing slash no redirect is done and the POST to the API works.
Is there a way to make this work no matter if a trailing slash or not?
Here is the .htaccess:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteBase /
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Here comes my routing and the controller:
$router->group(['prefix' => 'auth'], function ($router) {
$router->post('register', 'AuthController@register');
$router->post('login', 'AuthController@login');
$router->post('logout', 'AuthController@logout');
$router->post('refresh', 'AuthController@refresh');
$router->get('me', 'AuthController@me');
});
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!$token = Auth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
}