I have this controller:
class AuthController extends Controller
{
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'username' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'username' => $validatedData['username'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function me(Request $request)
{
return $request->user();
}
}
And here is my api.php file for the routes:
Route::post('/me', [AuthController::class, 'me'])->middleware('auth:sanctum');
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
So if I do this post request with POstman: http://127.0.0.1/api/register?name=luis ruiz flores&[email protected]&username=llrr00&password=password
I should get a json with the access_token and the token_type, but what I get is the login view of my webpage.
Any idea why this happens?
Thak you.
3
Answers
You should define Headers in postman to be {"Accept": "application/json"}
to let laravel know this request will be JSON, not a web response.
Try setting
Content-type
header toapplication/json
. I believe Laravel doesn’t allow a wildcardContent-type
like*/*
when it returns json. But I might be very wrong about it. I just had the same issue and thats how I managed to resolve it.Also the url shouldn’t be the way it is. You send your authentication info in url query params, but sensitive info, like passwords, should be sent with POST http method, and should be inside the request body. Notice the ‘body’ tab instead of ‘Params’ tab.
Setting Content-type in Postman
Post request in Postman
Controller
routes