php - Laravel & VueJS CORS Issue when trying to authenticate the user, even with the Cors middleware
Get the solution ↓↓↓I'm trying to make an authentication gateway for my project and I keep on getting a cors error like this:
I am using Laravel for the gateway and Vue.js for the front end. I have made a cors middleware like shown in this video
Here's my login function in Laravel
public function login(Request $request){
$loginCreds = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
if(!auth()->attempt( $loginCreds )){
return response()->json(['message'=>'Invalid login credentials.']);
}
$at = auth()->user()->createToken('authToken')->accessToken;
return response()->json(['user'=>Auth::user(), 'access_token' => $at]);
}
And here's my call I make from the front end
submitLogin() {
let params = new URLSearchParams();
params.append('email', this.email);
params.append('password', this.password);
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/login',
data: params
})
.then(res => {
console.log(res);
}).catch(err => console.log(err));
}
That setup gives me the error but if I do the same call but I have the following in my login function it doesn't give me the error
public function login(Request $request)
{
return \GuzzleHttp\json_encode('ok');
}
I don't know what to do, any help is appreciated, thank you in advance!
[Edit]
My Cors middleware
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
//ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
];
if ($request->getMethod() == "OPTIONS"){
//The client-side application can set only headers allowed in Access-Control-Allow-Headers
return response()->json('OK',200,$headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
And Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Cors::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
I use Laravel v7.14.1 and Laravel Passport for authentication
Answer
Solution:
[Edit]
Try to Update the header returned inapp/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header(�Access-Control-Allow-Origin’, �*’)
->header(�Access-Control-Allow-Methods’, �GET, POST, PUT, DELETE, OPTIONS’)
->header(�Access-Control-Allow-Headers’, �X-Requested-With, Content-Type, X-Token-Auth, Authorization’);
}
}
Source : Medium
[Alternative]
I'm usingfruitcake/laravel-cors
package, you may give it a try
Setup steps
1. Installation
Require the fruitcake/laravel-cors package in your composer.json and update your dependencies:
composer require fruitcake/laravel-cors
2. Publish Configuration
Publish the config to copy the file to your own config:config/cors.php
php artisan vendor:publish --tag="cors"
3. Usage
- 3.1 Global usage
To allow CORS for all your routes, add the HandleCors middleware in the$middleware
property ofapp/Http/Kernel.php
class:
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
- 3.2 ONLY for API Routes usage
To allow CORS for your API routes, add the HandleCors middleware in the$middlewareGroups
property ofapp/Http/Kernel.php
class:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Fruitcake\Cors\HandleCors::class,
],
];
Repo link
Hope it helps
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mysqli::real_connect(): (hy000/2002): connection refused
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.