Vue 3/Laravel POST http://localhost:5173/register 404 (Not Found) when create AxiosClient

549 Views Asked by At

When I try to register a new user I get an error back with axios.

enter image description here

This is my axios configuration and code where I want to use it:

Axios.js

import axios from "axios";
import store from "./store";

const axiosClient = axios.create({
    baseURL: `http://localhost:5173/`,
});

axiosClient.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${store.state.user.token}`;

    return config;
});

export default axiosClient;

Store/index.js

import { createStore } from "vuex";
import axiosClient from "../axios";

const store = createStore({
    state: {
        user: {
            data: {},
            token: sessionStorage.getItem("TOKEN"),
        },
    },
    getters: {},
    actions: {
        register({ commit }, user) {
            return axiosClient.post("/register", user)
                .then(({ data }) => {
                    commit("setUser", data);

                    return data;
                });
        },
        login({ commit }, user) {
            return axiosClient.post("/login", user)
                .then(({ data }) => {
                    commit("setUser", data);

                    return data;
                });
        },
    },

Also I don't know why, but by deafult I have # in my page url: http://localhost:5173/#/register

1

There are 1 best solutions below

3
cengsemihsahin On

Since a user that has not yet been authenticated in your Login and Register endpoints can send a request, you should not send the Authorization parameter in the header for requests made to them.

Here's how you can update your axios.js file with and without auth for to divide in two requests can be post:

Note: don't put / at the end of the URL (depending on your usage) even if you don't have or have a prefix.

import axios from 'axios';
import store from "./store";

const defaultPort = '5173';
const defaultLocalHostnames = [
    '127.0.0.1',
    'localhost'
];

const hostname = defaultLocalHostnames.includes(window.location.hostname) ?
    window.location.hostname + ':' + defaultPort :
    window.location.hostname;
const apiEndPoint = `${window.location.protocol}//${hostname}`;

/**
 * For Auth. Req. Routes
 */
const auth_req = axios.create({
    baseURL: `${apiEndPoint}/your-prefix-if-exists`,
});

auth_req.interceptors.request.use(config => {
    config.headers = {
        'Authorization': `Bearer ${store.state.user.token}`,
        'Accept': '*/*',
        'Content-Type': 'application/x-www-form-urlencoded'
    };
    return config;
});

/**
 * For Guest Routes
 */
const no_auth_req = axios.create({
    baseURL: `${apiEndPoint}/your-prefix-if-exists`,
});

no_auth_req.interceptors.request.use(config => {
    config.headers = {
        'Accept': '*/*',
    };
    return config;
});

export default {
    authRequired: auth_req,
    noAuthRequired: no_auth_req
};

Now you can use either one to fulfill your requests in store/index.js. For example:

login({ commit }, user) {
    return axiosClient.noAuthRequired.post('/login', user).then(({ data }) => {
        commit('setUser', data);
        return data;
    });
},

Finally run:

npm run dev OR npm run watch

Just in case, delete your old compiled files (chunks) before running them.

If you need to clear the cache on the server side, don't forget:

php artisan optimize:clear
php artisan route:cache

Basically, determining whether the routes you are accessing requires auth and sending parameters in the header accordingly will solve your problem.