After login, page should redirect on dashboard component and it does but then again redirect on laravel app url
Route : I have used Vue Router
const routes = [{
path: '/dashboard',
name: 'uDashboard',
component: uDashboard
}];
On Form Submit
methods: {
submit: function() {
axios.post('api/login', this.form).then(response => {
if (response.status == 201) {
this.$router.push({name: 'uDashboard'});
}
})
}
}
Make your code prevent the default action on form submit like so:
methods: {
submit: function(e) {
e.preventDefault(); // <-- added this
axios.post('api/login', this.form).then(response => {
if (response.status == 201) {
this.$router.push({name: 'uDashboard'});
}
})
}
}
Related
I have laravel as backend and next.js as frontend of my website.
I use laravel sanctum for authentication.
My laravel app and next.js app are in the same host, then I can use session-base sanctum for authentication without use token.
After login there is no problem when I want to access the routes that are protected with middleware aute:sanctum in client side of next.js but in the server side always get error unauthenticated.
This is my axios config and my function for fetch data in next.js:
// axios instance
const axiosInstance = axios.create({
baseURL: 'localhost:8000',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
});
const onRequest = (config) => {
if ((
config.method == 'post' ||
config.method == 'put' ||
config.method == 'delete'
/* other methods you want to add here */
) &&
!Cookies.get('XSRF-TOKEN')) {
return setCSRFToken()
.then(response => config);
}
return config;
}
const setCSRFToken = () => {
return axiosInstance.get('api/v1/csrf-cookie');
}
// attach your interceptor
axiosInstance.interceptors.request.use(onRequest, null);
// fetch data:
export async function getServerSideProps(context) {
const { query, req } = context;
const {
page,
search_term,
nip,
tableName
} = query;
try {
const response = await ax.post(`api/v1/admin/${tableName}`, { page: page, search_term: search_term, nip: nip || 10 }, {
withCredentials: true,
headers: {
Cookie: req.headers.cookie,
}
});
return {
props: {
initItems: response.data.data,
initMeta: response.data.meta,
initSearchTerm: search_term || '',
iniNip: nip || 10
}
}
} catch (err) {
console.log(err);
return {
notFound: true,
}
}
}
I am trying to add a Vue form component to my Laravel application so I can reuse it in a few places throughout the app. But when I submit the form I get a 422 error saying that the route is not found.
Form component:
<template>
<form #submit.prevent="mail" method="POST">
</form>
</template>
<script>
import FormMixin from '../FormMixin';
export default {
mixins: [ FormMixin ],
data() {
return {
'action': 'submit',
}
}
}
</script>
Form Mixin
export default {
data() {
return {
fields: {},
errors: {},
success: false,
loaded: true,
action: '',
}
},
methods: {
mail() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post(this.action, this.fields).then(response => {
this.fields = {}; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
},
}
Controller
public function mail(NewConctactRequest $contact) {
Mail::to('example#example.com')->send(new NewContact($contact));
return redirect()->route('thank you');
return response()->json(null, 200);
}
Web Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('adventures', 'PageController#adventures')->name('adventures');
Route::get('crew', 'PageController#crew')->name('crew');
Route::get('events', 'PageController#events')->name('events');
Route::get('gallery', 'PageController#gallery')->name('gallery');
Route::get('thank_you', 'PageController#thank_you')->name('thank you');
Route::get('contact', 'ContactController#show')->name('contact');
Route::post('submit', 'ContactController#mail')->name('mail contact');
I have Axios installed already and the CSRF token is set in the head pf the document. When I use the form as just a standard form (not using Vue) it submits properly.
im working with vue & laravel.i have a edit profile page with some forms in it(name,email,...)
the default value of this form not showing for the first time, but if user refresh the page everything will be work!!!
<template>
<label>Name:</label>
<input type="text" v-model="name">
<label>Email:</label>
<input type="email" v-model="email">
<template>
<script>
export default {
data () {
return {
name:'',
email:'',
}
},
mounted : function(){
this.getVueItems();
},
methods: {
getVueItems: function(){
axios.get('./api/auth/me').then(response => {
var vm = this;
vm.name = response.data.name;
vm.email = response.data.email;
});
},
getAuthUser () {
this.user = this.$store.getters.currentUser
},
updateAuthUser () {
this.submiting = true,
axios.put('./api/auth/update', {
name:this.name,
email:this.email,
})
.then(response => {
// this.submiting = false;
location.reload(true);
// success();
})
.catch(error => {
this.submiting = false;
})
},
}
}
</script>
whats is the problem?
As you are using arrow function this keyword is already accessible inside the function.
And for this you should first check in console if you are getting proper response value from api in console.
Hence change your function as below and check once.
async getVueItems() {
await axios.get('./api/auth/me').then(response => {
console.log(response);
this.name = response.data.name;
this.email = response.data.email;
});
i have created login with rest-full api login system with vue 2 laravel
i want after login it should redirect to another page like /
i have tried with add then redirect: '/'
here is my script
<script>
export default {
data(){
return{
loginDetails:{
email:'',
password:'',
remember:true
},
errorsEmail: false,
errorsPassword: false,
emailError:null,
passwordError:null
}
},
methods:{
loginPost(){
let vm = this;
axios.post('/login', vm.loginDetails)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
var errors = error.response
if(errors.statusText === 'Unprocessable Entity'){
if(errors.data){
if(errors.data.email){
vm.errorsEmail = true
vm.emailError = _.isArray(errors.data.email) ? errors.data.email[0]: errors.data.email
}
if(errors.data.password){
vm.errorsPassword = true
vm.passwordError = _.isArray(errors.data.password) ? errors.data.password[0] : errors.data.password
}
}
}
});
}
},
mounted() {
}
}
this may help
loginPost(){
axios.post('/login', this.loginDetails)
.then(function (response) {
if(response.status === 200) {
this.$router.push({ path : '/' });
}
})
}
I keep getting this error in my client/app.js file as I use grunt to compile it into production. I never had this error before while in development. I've not found any clear guidance on how to fix this on the client side. I initialize Parse at the bottom of the page.
My app.js:
'use strict';
angular.module('cpApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'ui.bootstrap',
'parse-angular',
'angularPayments',
'elif'
])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
$urlRouterProvider
.otherwise('/');
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('authInterceptor');
})
.factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to Landing Page
responseError: function(response) {
if(response.status === 401) {
$location.path('/');
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
.run(function ($rootScope, $location, Auth) {
Parse.initialize('key1', 'key2');
// Redirect to card if route requires auth and you're not logged in
$rootScope.$on('$stateChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
$location.path('/');
}
});
});
});
The issue was in my config function. I needed to move Parse there from run:
.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, Parse) {
Parse.initialize('Id1', 'Id2');
$urlRouterProvider
.otherwise('/');
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('authInterceptor');
})