我目前正在用Laravel编写API,但遇到了一些麻烦。目前,我专注于api的身份验证部分,因此我有以下路线:
(通过php artisan route:list
)
+--------+--------+------------------------+------+--------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+--------+------------------------+------+--------------------------------------------------------+------------+
| | POST | v1/users/auth/login | | App\Http\Controllers\User\AuthController@login | api |
| | POST | v1/users/auth/register | | App\Http\Controllers\User\AuthController@register | api |
+--------+--------+------------------------+------+--------------------------------------------------------+------------+
非常简单。现在,当我尝试通过邮递员发布到v1/users/auth/login
时,它可以工作。它给了我预期的响应和一切。但是,当我尝试register
路线时,Laravel抛出404吗?
没有错误,什么也没有,只有一个404。现在,通过一些穴居调试,我可以看到它通过了请求的authorize()
方法,但是随后又抛出了该织补错误。
这是我的要求:
class RegistrationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return !Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'code' => 'required',
'username' => 'required|unique:users',
'password' => 'required|confirmed|min:6',
];
}
public function persist()
{
$user = User::create([
'username' => $this->username,
'password' => password_hash($this->password, PASSWORD_DEFAULT),
'reg_ip' => $this->ip(),
'last_ip' => $this->ip()
]);
return response()->json($user->api_token, 201);
}
如何明确定义我的路线,这怎么可能?
谢谢。
-编辑:
我的控制器:
class AuthController extends Controller
{
public function register(RegistrationRequest $request)
{
return $request->persist();
}
public function login(LoginRequest $request)
{
return $request->persist();
}
}
答案 0 :(得分:0)
在此路线上添加前缀
v1/users/auth/login
这样使用
api/v1/users/auth/login
答案 1 :(得分:0)
要在laravel中调用api路由,请将api /作为该路由的前缀添加,否则它将在web.php中搜索路由