May 15, 2019
0
Level 5
Restful Api Laravel + React JS
Hey guys I'm trying to get a user data from an api using react connected to my laravel back end app
the issue is I'm always getting '401 unauthorized" even though when I test my api on postman it works correctly and I passed the same headers in the api call
I didn't know how to fix that
This is my route :
Route::group(['prefix'=>'api','module' => 'User','middleware' => ['auth:api','CORS'], 'namespace' => 'App\Modules\User\Controllers'], function() {
Route::get('/get/user','UserController@handleGetUser');
});
This is the function
public function handleGetUser(){
return response()->json(['statut'=>200,'user'=>Auth::user()]);
}
This is CORS middleware
<?php
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: * ');
header('Access-Control-Allow-Headers: Content-type, X-Auth-Token, Authorization , Origin ');
return $next($request);
}
}
This is the call in my react app
export const getProfile = () => {
axios.get(`http://localhost/crud-app/public/api/get/user`,
{ 'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization' : `Bearer ${localStorage.userToken}` })
.then(res => {
console.log(res);
})
}
Please or to participate in this conversation.