How to set URL for axios? - laravel

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

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 interceptors not working and nothing return

I have problem with axios interceptors. I try set header for jwt using interceptors but nothing work so I changed my code and added only console.log to this code. When I open console in Chrome nothing is displayed. Do you have any idea what the problem could be?
import axios from 'axios'
const baseURL = 'http://localhost:8080'
const instance = axios.create({
baseURL,
params: {}
})
instance.interceptors.request.use(function (config) {
console.log('test');
return config;
}, function (error) {
return Promise.reject(error)
})
export default instance
I just took a look into an old project that I used interceptors. There I called it directly on the axios object.
Perhaps something like the code bellow will work.
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8080';
axios.interceptors.request.use(function (config) {
console.log('config', config);
return config;
}, function (error) {
return Promise.reject(error)
});
export default instance;

The difference between axios and this.$axios

I am developing using nuxt and gridsome.
These are all vue frameworks and I found that there are something interesting.
When I do like this:
<script>
import axios from 'axios';
...
created: function created() {
axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
this.options=res.data.map(function(data){
return {name: data.url, provider_id: data.provider_id};
});
}
I got 401 error(backend is laravel).
message: "Unauthenticated."
But when I use this, it's working.
<script>
import axios from 'axios';
...
created: function created() {
this.$axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
this.options=res.data.map(function(data){
return {name: data.url, provider_id: data.provider_id};
});
}
It's because Axios allows to create instances of itself which you can therefore customize. So when you do axios.get, underlying, Axios creates an instance on the fly before using it. When you do this.$axios.get, you use an already created instance which got customized somewhere else in your code (by adding some HTTP headers for example)

Get data from Laravel(in api folder) to Vue (placed in another folder)

I have Laravel in api folder and Vue is in the root folder, and I try to pass data from Laravel to Vue Components.From what I find I must use axios for this but I didn't know how. I am looking for a solution for some hours now, but nothing worked. PS. I didn't do anything in blade till now. Any help, please !?
api/routes/api.php
Route::get('/content', 'ContentController#index');
ContentController
public function index() {
$customers = Customer::all();
return $customers;
}
Vue component
<template>
</template>
<script>
import axios from 'axios'
export default {
name: "Home"
};
</script>
Since you created your Vue app using the Vue CLI, running vue serve starts your application at a local URL, you need to have your Laravel API app running as well so you can request data from it using Axios in Vue components
cd api
php artisan serve
Then in your template, you should have something like this
<template>
<div></div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
databaseConfiguration: "",
errors: {}
};
},
name: "Home",
created: function() {
axios
.get("http://127.0.0.1:8000/api/content")
.then(response => {
this.databaseConfiguration = response.data;
console.log(response.data);
})
.catch(error => {
this.errors.push(error);
console.log(error);
});
}
};
</script>
Here's a full working example app on GitHub
Hope this helps

Vue.js Google / Microsoftgraph login

I have a Laravel app and I am using vue.js and vue-authenticate to have a user login with their Microsoft account. The vue.js app is living under a laravel route not Laravel home page i.e. if the homepage route is / then the vueapp route is /vueapp.
On the vueapp's home page I have the Login with Microsoft button configured. In my vue app the base url is set to mydomain/vueapp. I can successfully authorize the app with my Microsoft account but then instead of being able to see a success message and a token, I see the following error:
Error: Request failed with status code 405
I have Axios and Vuex installed and my vue routes are supported in the hash mode instead of history because of some weird laravel issue.
Update: I am seeing a similar issue with Google. It seems like something happens when the URI is redirected.
Update: Below is my code:
For my component:
<script>
import store from '../store'
import axios from 'axios'
export default{
data () {
return {
}
},
methods: {
authenticate: function (provider) {
console.log("Login Started" + provider);
this.$auth.authenticate(provider).then((response) => {
console.log("Login Successful " + response);
}).catch(error => {
console.log("error occured ");
console.log(error);
})
}
},
}
</script>
My HTML ---
auth Live
auth Google
In my app.js
import Vue from 'vue'
import lodash from 'lodash'
import VueLodash from 'vue-lodash'
import VueAxios from 'vue-axios'
import VueAuthenticate from 'vue-authenticate'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.use(VueLodash, lodash)
Vue.use(require('vue-moment'));
import vmodal from 'vue-js-modal'
Vue.use(vmodal, {
dialog: true,
dynamic: true,
})
import Toasted from 'vue-toasted';
Vue.use(Toasted, 'top-center')
Vue.use(VueAxios, axios)
Vue.use(Vuex)
import VueAuthenticate from 'vue-authenticate'
Vue.use(VueAuthenticate, {
baseUrl: 'https://www.mywebsite.com', // Your API domain
providers: {
live: {
clientId: 'My Mcirosoft key',
redirectUri: 'https://www.mywebsite.com/auth/live' // Your client app URL
},
google: {
clientId: 'mygooglekey.apps.googleusercontent.com',
redirectUri: 'https://www.mywebsite.com/auth/google'
}
}
})
In laravel - I have the following routes. Webapp is the folder where vue app lives and it uses the hash mode for routing not history.
Route::get('webapp/{path?}', function () {
return View::make('app');
})->where( 'path', '([A-z\d-\/_.]+)?' );
Route::get('auth/live', function () {
return View::make('app');
});
Route::get('auth/google', function () {
return View::make('app');
});

Resources