WmZilla - Webmaster and Marketplace

The Next Generation Webmaster and Trade Forum

CORS Error Issue when adding HasApiTokens in Laravel

DoyaCat

New member

0

0%

Status

Offline

Posts

48

Likes

0

Rep

0

Bits

250

3

Months of Service

0%
Hello everyone, I hope you can help me with an issue I'm experiencing in Laravel (I'm new to this so I might be missing something).

I have a Laravel 11 backend (as a REST API) and a front end built with React. Before explaining the specific error, let me share a working function.

Function in Laravel controller to change password:

```php
public function changePassword(Request $request)
{
// Validate input data
$validator = Validator::make($request->all(), [
'token' => 'required|string',
'password' => 'required|string',
]);

// Check if there is a password reset token request
$requested = PasswordResetToken::where('token', $request->token)->first();

if ($requested) {
$user = User::where('email', $requested->email)->first();

// Confirm email existence and change password
if ($user) {
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['success' => 'Password changed successfully'], 200);
} else {
return response()->json(['error' => 'User not found'], 401);
}
} else {
return response()->json(['error' => 'Error with token request'], 401);
}
}
```

Now, here is the issue. I have the following "login" function in the same controller:

```php
public function login(Request $request)
{
$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials)) {
$token = auth()->user()->createToken('Token')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'Incorrect credentials'], 401);
}
}
```

When I call this function, I get the error: "Call to undefined method App\\Models\\User::createToken()". So, I checked the model and added "HasApiTokens" as I found through Google:

```php
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens;
}
```

After adding this, the first call to "changePassword" gives me a CORS error: "has been blocked by CORS policy: No 'Access-Control-Allow-Origin'". The second call to "login" no longer shows the createToken error but also gives a CORS error: "has been blocked by CORS policy: No 'Access-Control-Allow-Origin'".

Why does adding HasApiTokens to the User model result in a CORS error? What am I doing wrong or what do I need to check?
 

249

6,622

6,642

Top