I am a bit new to VueJS and I want to get data from an Laravel (passport) API, so for that I used npm i axios
for API requests and this is my script code from App.vue file:
import axios from 'axios';
export default {
data () {
return {
}
},
created() {
const postData = {
grant_type: "password",
client_id: 2,
client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
username: 'my-email@gmail.com',
password: '********',
scope: ''
}
axios.post('http://localhost/api/oauth/token', postData)
.then(response => {
console.log(response.data.access_token);
const header = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + response.data.access_token,
};
axios.get('http://localhost/api/api/user', {headers: header})
.then(response => {
console.log(response)
})
})
}
}
The API.PHP (routes file for API):
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
And this is the Middleware code for CORS fixing in Laravel:
public function handle($request, Closure $next)
{
$domains = ["http://localhost:8080"];
if (isset($request->server()['HTTP_ORIGIN'])) {
$origin = $request->server()['HTTP_ORIGIN'];
if (in_array($origin, $domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
}
}
return $next($request);
}
Look at the console.log(response.data.access_token)
, I am getting the token logged in the console but the next request gives me 401 unauthorized error, I tried many solutions but not worked, any suggestions?