我正在创建一个用于身份验证和数据库管理的 Laravel API。在我的 AuthController 中,我有一个运行良好的登录函数和一个不起作用的注册函数。它不返回新用户信息和 201 状态,而是返回 200 并显示 API 的主页(由 Laravel 创建的welcome.blade.php)。我在 api.php 中的路线:Route::post('login', 'AuthController@login');Route::post('register', 'AuthController@register');我的验证控制器:class AuthController extends Controller{ /** * Register user */ public function register(Request $request) { $request->validate([ 'firstname' => 'required|string', 'surname' => 'required|string', 'email' => 'required|email|unique:users', 'password' => 'required|string|confirmed' ]); $user = new User([ 'firstname' => $request->firstname, 'surname' => $request->surname, 'email' => $request->email, 'password' => bcrypt($request->password) ]); $user->save(); $success['token'] = $user->createToken('MyApp')->accessToken; $success['firstname'] = $user->firstname; $success['surname'] = $user->surname; $success['email'] = $user->email; return response()->json(['success' => $success], 201); } /** * Login user and create token * * @param [string] email * @param [string] password * @param [boolean] remember_me * @return [string] access_token * @return [string] token_type * @return [string] expires_at */ public function login(Request $request) { $request->validate([ 'email' => 'required|email|exists:users,email', 'password' => 'required|string', // 'remember_me' => 'boolean' ]); $credentials = request(['email', 'password']); if(!Auth::attempt($credentials)) { return response()->json([ 'message' => 'Unauthorized', 'request'=> $credentials ], 401); }注册函数有什么问题?
1 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
我想这是为了你的验证。当验证失败时,您必须返回一个 json,否则它将返回最后一个视图。像这样进行验证
$validator = Validator::make($request->all(), [
'firstname' => 'required|string',
'surname' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|string|confirmed'
]);
if ($validator->fails()) {
return response()->json(['message' => $validator->errors()->first(), 'status' => false], 500);
}
并记住使用 Validator 类
use Illuminate\Support\Facades\Validator;
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报
0/150
提交
取消