0
votes

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?

1
http://localhost/api/api/user should be http://localhost/api/user Not?Vikash Pathak
no http://localhost/api that's my project-name and the next api is for accessing the API Routes.user11608775
Please share the route configuration.Vikash Pathak
Check now I have updated!user11608775
for the time being please remove the domain validation from the cors settings..Vikash Pathak

1 Answers

0
votes

you need to send the token with axios request in the header so the backend knows its legit, you can only do that after you check your backend is working fine with postman, now you can set the axios header like this axios.defaults.baseURL = '/api'; axios.defaults.headers.common['Authorization'] = "Bearer " + your_token_variable