0

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);
    }    
}
Mike
  • 5,416
  • 4
  • 40
  • 73
  • Please see https://stackoverflow.com/a/47031102/4903314 and https://stackoverflow.com/a/47012740/4903314 – Umair Khan Aug 17 '20 at 12:30
  • Already checked for Cors. Not the problem. – Mike Aug 17 '20 at 12:31
  • Then this question needs more details like the url of your api, the html form that you are using to post data or similar logic in JS or similar language. Also please check if you are making non ssl request to ssl resource and vice versa. – Umair Khan Aug 17 '20 at 12:34
  • Some web servers are also configured to redirect requests that has trailing slashes to the same URL without trailing slashes, or vice versa. You need to do some more debugging and give us more info. – M. Eriksson Aug 17 '20 at 12:38
  • @MagnusEriksson yeah the slashed are the problem. i will extend the question. – Mike Aug 17 '20 at 13:01

0 Answers0