skip to Main Content

I have a problem in getting some data in my database. It returns HTML data.

{data: '<!DOCTYPE html>n<html lang="en">n    <head>n      …>n    x3Cscript src="/js/app.js">x3C/script>n</html>n', status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…},…}

And I am only requesting an authenticated user’s username. Here are my codes:

Vue.JS 3.0.0 Vuex


const api = axios.create({
    baseURL: '/accounts',
});

async getCurrentUser(context, payload) {
            try {
                const response = await api.get('/accounts/get-user');
                console.log(response)
                context.commit('setUserLogged', response.data.current_user);
            } catch (error) {
                console.log(error)
            }
        }

Getters:

mounted(){
    this.$store.dispatch('getCurrentUser')
},
computed: {
    ...mapGetters(['getUserLogged']),
    isLogged(){
        if(localStorage.getItem("auth_token")) {
             return true
        }
    return false
    },
},

My AuthController:

public function get_logged_user(){
        $user_logged = auth()->user();
        return response()->json(['current_user' => $user_logged, 'result' => 'Success' ]);
    }

And my route:

Route::prefix('accounts')->group(function(){
    Route::get('/get-user',[AuthController::class, 'get_logged_user'])->name('get_logged_user');
    // other routes here...
})

I already added the bootstrap.js required codes:

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;

2

Answers


  1. You need to set content type.
    According Axios’s https://github.com/axios/axios/issues/86
    You need to add data:{}

    axios.get('url', {
        headers: {
            'Content-Type': 'application/json',
        },
        data:{}
    })
    
    Login or Signup to reply.
  2. You can also solve your issue with a server-side approach. You can create a ForceJsonMiddleware to automatically add the required header to force your Laravel API to return JSON.

    Here is an example of middleware that I use in most of my projects:

    use Closure;
    use IlluminateHttpRequest;
    
    class ForceJsonMiddleware
    {
        public function handle(Request $request, Closure $next)
        {
            $request->headers->set('Accept', 'application/json');
            return $next($request);
        }
    }
    

    Then, depending on your needs, here’s how you should register it in your app/Http/Kernel.php file:

    You want to apply it to all routes of your Laravel API ?:

        protected $middleware = [
            // AppHttpMiddlewareTrustHosts::class,
            AppHttpMiddlewareTrustProxies::class,
            ...
            ForceJsonMiddleware::class, // <-- add it here
            HandleCors::class
        ];
    

    You want to apply it only to certain routes ?
    Create an alias :

        protected $middlewareAliases = [
            'auth' => AppHttpMiddlewareAuthenticate::class,
            ....
            'forcejson' => ForceJsonMiddleware::class, // <-- add it here
        ];
    

    And use it on your route file :

    Route::get('/test', [TestController::class, 'testMethod'])->middleware('forcejson');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search