I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios
for making API requests. Below is the script code from my App.vue file:
import axios from 'axios';
export default {
data () {
return {
}
},
created() {
const postData = {
grant_type: "password",
client_id: 2,
client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e98490c48c84888085a98e84888085c78a8684">[email protected]</a>',
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();
});
Also, here is the Middleware code used for fixing CORS 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);
}
Despite seeing the token logged in the console with
console.log(response.data.access_token)
, I encounter a 401 unauthorized error with the subsequent request. I have tried various solutions without success. Any advice or suggestions would be greatly appreciated.