2

I want to ask for help regarding Axios' response to my POST request in the login route via Laravel. It returns HTML of the homepage in data when it authenticated the user (or it finds the user in the database). Please see the response screenshot below:

Axios Response in /login POST request (success)

May I just ask for the solution to my problem? Here are the necessary codes and the versions that I am using:

Tools

VueJS: v3.0.5 Axios: 0.19 Laravel: 5.8

Codes

Login.vue (script)

import axios from 'axios'

export default {
    data() {
        return {
            csrfToken: '',
            loginObj: {
                username: '',
                password: '',
                remember: false,
            },
            message: '',
        }
    },
    created() {
        this.csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    },
    methods: {
        signIn() {
            console.log(this.loginObj)

            axios.post('login', this.loginObj).then(res => {
                console.log(res)
            })
            .catch(error => {
                console.log(error.response)
            })
        }
    }
}

Login.vue (template)

<div class="card shadow-lg border-0 rounded-lg mt-5">
    <div class="card-header bg-orange"><h3 class="text-center my-4">Hello!</h3></div>
    <div class="card-body p-0">
        <div class="row">
            <div class="col-lg-6 d-none d-lg-block">
                <div class="login-image-wrap text-center">
                    <img src="/img/ahrs_logo_trans.png" class="login-img" alt="AKB Logo">
                </div>
            </div>
            <div class="col-lg-6">
                <div class="p-5">
                    <div class="text-center">
                        <h1 class="h4 text-gray-900 mb-4">Sign In</h1>
                    </div>
                    
                    <form name="loginForm" @submit.prevent="signIn">
                        <input type="hidden" name="_token" :value="csrfToken">
                        <div class="form-group">
                            <label class="small mb-1" for="inputUsername">Username</label>
                            <input class="form-control py-4" v-model="loginObj.username" id="inputUsername" type="text" placeholder="Enter username" required autofocus>
                        </div>
                        <div class="form-group">
                            <label class="small mb-1" for="inputPassword">Password</label>
                            <input class="form-control py-4" v-model="loginObj.password" id="inputPassword" type="password" placeholder="Enter password" required>
                        </div>
                        <div class="form-group">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="remember" id="remember" v-model="loginObj.remember">

                                <label class="form-check-label text-small" for="remember">
                                    Remember Me
                                </label>
                            </div>
                        </div>
                        <div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0">
                            <a class="small" href="password.html">Forgot Password?</a>
                        </div>
                        <hr />
                        <div>
                            <button type="submit" class="btn bg-yellow btn-block font-weight-bold">LOGIN</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

LoginController.php

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

// override in the AuthenticatesUsers function username()
public function username()
{
    return 'username';
}

Thank you for your help.

1
  • Are you using the default bootstrap.js file that comes with Laravel? Are you wanting it to return the user JSON data instead? Commented Jan 13, 2021 at 8:20

1 Answer 1

1

You will probably need to tell Laravel that you want to return the User as JSON if it's an ajax request.

You can do this by adding the following to your LoginController:

protected function authenticated(Request $request, $user)
{
    if ($request->ajax()) {
        return $user;
    }
}

You may also need to set the X-Requested-With header that is usually set in the default bootstrap.js file that comes with Laravel so that Laravel knows it's an ajax request:

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Obviously, if this line is already there and you're still including the bootstrap file in your bundle you can ignore this.

Sign up to request clarification or add additional context in comments.

7 Comments

Hello. Yes. I am using the bootstrap.js in Laravel (resources/js/bootstrap.js) and it have this code:
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
may I ask what to put in the LoginController to tell Laravel that I want the user as JSON?
Sorry @MarkJerlyBundalian, I must not have hit save when I added the authenticated() method to my answer. I've updated it now. Also, since you've got axios set on the window object, you shouldn't need to import it into your component as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.