我制作的小型REST API在本地运行良好。在服务器上传输时,GET请求都能正常工作,但POST不能。
我读过很多人都有这种效果,大多数时候的问题是路线错误。
看起来尾部斜线会创建重定向,从而导致问题。如果没有尾部斜杠,就不会进行重定向,并且到API的POST也能工作。
有没有一种方法可以让这个工作,无论是否有尾随斜线?
以下是.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>
下面是我的路由和控制器:
$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);
}
}