Axios differentiate between local and prod? - ajax

I am using Vue + axios and I am having trouble setting it up so that base url will be different depending on url of the site?
so my localhost for vue is of course:
http://localhost:8080
api for localhost is:
http://webuilder.app
on the server vue is:
http://webuilder.co.uk
and api is:
http://api.webuilder.co.uk
So I am using webpack to combine common libraries:
'vendor.js': ['vue', 'bootstrap', 'axios', 'popper.js', 'pace', 'vue-router', 'jquery'],
and my global config:
import Popper from 'popper.js/dist/umd/popper.js';
import Pace from 'pace-js';
import Vue from 'vue';
import VueRouter from 'vue-router';
import Axios from 'axios';
Pace.start();
try {
window.$ = window.jQuery = require('jquery');
window.Popper = Popper;
require('bootstrap');
} catch (e) {}
window.Vue = Vue;
window.VueRouter = VueRouter;
window.axios = Axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
So if I want to do axios post it works fine but each time I have to tell it what domain it is going to, is there some kind of setup so that when I am on localhost, domain is webuilder.app while if it's on prod domain is api.webuilder.co.uk?

Consider using something like this
var axios = require('axios');
var axiosInstance = axios.create({
baseURL: process.env.baseUrl || 'https://example.com/foo/bar'
});
module.exports = axiosInstance;
Use this in a conditional statement where you set the enviroment to prod or develop

Related

Laravel Vue3 - Passing Token and User info to Vue store

I'm creating a Laravel/Vue3 app and wanted to completely separate the Laravel router from the SPA router.
In order to achieve this I created a dashboard.blade.php file which contains the following content:
<x-app-layout>
<div id="app"></div>
</x-app-layout>
Vue then simply mounts on top of that div and the app is started.
My webpack.mix.js:
const mix = require("laravel-mix");
mix.ts("resources/js/app.ts", "public/js")
.vue({ version: 3 })
.postCss("resources/css/app.css", "public/css", [
require("postcss-import"),
require("tailwindcss"),
require("autoprefixer"),
]);
The app.ts file is also quite simple:
import { createApp } from 'vue';
import App from './App';
createApp(App).mount('#app');
Which is great, but my holdup is that for subsequent requests (via Axios), I will need the user token. How can I get this token/logged in user info to my Vue3 app?
I'm using Laravel Breeze for authentication (if that helps).
Thank you,
It turns out the answer was 'extremely' simple. I had to do nothing besides removing the comment tags on this line:
And add headers as follows in your axios config:
import axios from "axios";
import store from "../store";
const Axios = axios.create({
baseURL: process.env.APP_URL,
headers: { Accept: "application/json" },
});
Axios.interceptors.request.use(
(config) => {
store.commit("setLoader", true);
return config;
},
(error) => Promise.reject(error)
);
Axios.interceptors.response.use(
(response) => {
store.commit("setLoader", false);
return response;
},
(error) => Promise.reject(error)
);
export default Axios;
Subsequent axios calls have the token attached automatically.
You can find all the required information here. Love Laravel...

Vue js router not loading page if i'm passing token from router.js

I'm using vue js with laravel api . i have defined router for forget password page in url i'm passing token . when i'm passing token then page not loading its coming not found.
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Router from 'vue-router'
import ResetPasswordForm from './pages/ResetPasswordForm'
Vue.use(Router)
const routes = [{
path: 'reset-password/:token',
name: 'ResetPasswordForm',
component: ResetPasswordForm
}]
export default new Router({
mode: 'history',
routes
})
web.php
Route::any('{slug}', function () {
return view('welcome');
});
please help me how to fixed out this issue.

How to set URL for axios?

I am creating a request from client with nuxtjs to laravel server. but the url request sent is http://localhost:3000/undefined/api/auth/signin instead of http://127.0.0.1:8000/api/auth/signin. I know this is simple question but I can't figure out how it works with nuxt and laravel
.env file
APP_URL=http://127.0.0.1:8000/
CLIENT_URL=http://localhost:3000/
import axios from 'axios'
const API_URL = process.env.APP_URL +'/api/'
...
axiosPost(urlSuffix, data) {
return axios.post(API_URL + urlSuffix, data, {
useCredentials: true,
headers: authHeader()
})
.then(response => {
return response.data
})
...
If you are using laravel-mix, (React, Vue or even Vanilla JS file which compiled by mix):
In your Javascript file:
import axios from 'axios'
const API_URL = process.env.MIX_APP_URL +'/api/'
// rest of your code...
Add this in your .env file:
MIX_APP_URL="${APP_URL}"
And re-compile your scripts by npm run prod, or npm run dev or npm run watch. Whichever you need.
If you are using in blade file, process.env isn't accessible there. Instead, add this:
const API_URL = {{url('/')}} +'/api/'
If you are using standalone nuxt.js:
Add in nuxt.config.js
export default {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
appUrl: process.env.APP_URL,
}
}
And in your js file:
import axios from 'axios'
axios.create({
baseURL: process.env.appUrl
});
// rest of your code

router not defined when calling inside a vuex action

Am using Vuex in my Laravel app and for some reason, I cannot do route.push inside an action.
My app.js:
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router'
import { routes } from './routes'
import store from './store/store'
Vue.use(VueRouter)
Vue.component('app-component', require('./App.vue').default);
Vue.component('appRegister', require('./components/User/Register.vue').default);
Vue.component('appLogin', require('./components/User/Login.vue').default);
const router = new VueRouter({
mode: 'history',
routes
})
const app = new Vue({
el: '#app',
router,
store
});
Inside my Login controller, I have a method called login which looks like the following:
login(){
this.$store.dispatch('login', this.user);
}
Then my login action looks like this:
login: ({commit}, user) => {
state.users.map(u => {
if(u.email == user.email){
router.push('/');
}
});
}
When I click on the button, I see the following error in the console:
[Vue warn]: Error in v-on handler: "ReferenceError: router is not defined"
Note, if I do the following inside the Component method, it works fine:
login(){
this.$router.push('/');
}
How can I do the route push inside the vuex action?
I looked at this answer here but it does not seem to solve my problem.
I imported vue-router inside app.js
You have to define your vue router in your login controller or import your router into your login controller.

Vue.js router view no components?

I am trying to make a vue SPA using vuex, vue-router & laravel for backend. I was separating our data on our app.js to try to reduce clutter and keep our code neat. When everything on one page it works as intended, loading the routes in the router. But when we separate the code to make it more modular into: app.js, boostrap.js, routes.js, and store.js
The components aren't loading in our router-view and we are able to see our RouterLink
app.js
// Require the bootstrapper
require('./bootstrap');
// Grab imports
import Store from './store';
import Router from './routes';
// Views
import App from './views/App';
// Create the application
const app = new Vue({
el: '#heroic',
components: { App },
store: Store,
router: Router
});
boostrap.js
// Imports
import Vue from 'vue';
import Axios from 'axios';
import Swal from 'sweetalert2';
// Add to window
window.Vue = Vue;
window.Axios = Axios;
// Add Axios headers
window.Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.Axios.defaults.headers.common['Authorization'] = 'Bearer ' + 'token';
window.Axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
routes.js
// Imports
import Vue from 'vue';
import VueRouter from 'vue-router';
import Store from './store';
// Set to use
Vue.use(VueRouter);
// Views
import Hello from './views/Hello';
import Home from './views/Home/';
import UserIndex from './views/UserIndex';
// Create our routes
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/hello',
name: 'hello',
component: Hello,
},
{
path: '/users',
name: 'users.index',
component: UserIndex,
}
];
// Create the router
const router = new VueRouter({
mode: 'history',
routes: routes,
scrollBehavior (to, from, saved) {
if (saved) {
return saved;
}
return { x: 0, y: 0};
}
});
// Before every request
router.beforeEach((to, from, next) => {
});
// After every request
router.afterEach((to, from, next) => {
});
// Export
export default router;
hello.vue
<template>
<div class="row row-cards row-deck">
<div class="col-lg-4 col-md-6">
<p>Hello World!</p>
</div>
</div>
</template>
store.js
// Imports
import Vue from 'vue';
import Vuex from 'vuex';
import PersistedState from 'vuex-persistedstate';
import Cookie from 'js-cookie';
// Set use
Vue.use(Vuex);
// Create our store
const store = new Vuex.Store({
state: {
auth: [{
id: 1,
username: '',
motto: '',
rank: 1,
permissions: [],
token: ''
}],
users: [],
},
mutations:{
},
actions: {
},
getters: {
}
});
// Export
export default store;
The expected result is that when I visit the "/hello" route it would show the information that says "Hello world!" that is within the Vue file specified as the component in the routes section of the router. Instead using my Vue DevTools I get the following with no Hello world on the page.
https://i.pathetic.site/chrome_99Mbxf7f0c.png
My guess is the router is stuck waiting for the beforeEach (and also possibly afterEach) hook to be resolved. You need to call next().
Also unrelated, but if you’re using modules then you shouldn’t need to assign stuff on window.

Resources