axios.post() doesn't get any response - ajax

I am using laravel 5.6 and vue.js. While sending ajax post request to login:
<script>
import axios from 'axios'
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
email: '',
password: '',
remember: false
}
},
computed: {
validateFields(){...}
},
created: function(){
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
},
methods: {
validateEmail(){...},
attemptLogin(){
axios.post('/login', {
email: this.email,
password: this.password,
remember: this.remember
}).then(resp => {
console.log(resp)
}).catch(error => {
console.log(error.mesage)
});
}
}
}
</script>
I don't get any response, though while debugging I see that request has correct data ([request with data, but not response])1
CSRF is enabled on the app, but it is included in the layout header :
<meta name="csrf-token" content="{{ csrf_token() }}"> and axios registers it automatically. What might be the issue? Thanks.

Related

Nuxtjs and Scatum duplicate requests and no cookie stored

I am facing a weird problem. I have a Laravel API server setup and a Nuxtjs frontend. I am using LaravelSanctum Provider in Nuxtjs. I am able to send request and the authentication and data retrival is fine. However, the cookies doesn't seem to get stored in my local storage.
login.vue
<script>
export default {
async login() {
this.$auth.loginWith('laravelSanctum', {
data: {
email: 'test#gmail.com',
password: 'test',
},
})
},
}
</script>
nuxt.config.js
axios: {
baseURL: 'http://local.api.test/api/v1/',
proxy: true,
credentials: true,
},
proxy: {
'/laravel': {
target: 'http://local.api.test/api/v1/',
pathRewrite: { '^/laravel': '/' },
},
},
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://local.api.test',
endpoints: {
login: {
url: '/api/v1/login/admin',
},
user: {
url: '/api/v1/admin',
},
},
},
},
},

in nuxt.js SSR i was created authentication system using laravel sactum im facing redirecting error

nuxt.js I'm implemented an SSR authentication system using Laravel sanctum but I'm facing Redirecting issue.
When I have entered login credentials after summited my LOGIN button it Was not redirected to Dashboard it still on the login page if I need to visit Dashboard I need to manually enter the dashboard URL same thing on logout.
nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'hello',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
router: {
middleware: ['auth'],
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {},
auth: {
strategies: {
'laravelSanctum': {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
endpoints: {
login: {
url: "/api/login"
},
logout: {
url: "/api/logout"
},
user: {
url: "/api/user"
}
},
user: {
property: false
}
}
},
redirect: {
login: "/login",
logout: "/",
home: "/dashboard"
}
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
babel: {
plugins: [
['#babel/plugin-proposal-private-methods', { loose: true }]
]
}
}
}
middleware
export default ({ app, redirect }) => {
if (app.$auth.loggedIn) {
return redirect("/");
}
};
Login Page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Login">
<b-button variant="primary" #click="login()">Login</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
middleware: ["guest"],
data() {
return {
form: {
email : "john#email.com",
password : "123321"
}
};
},
methods: {
login() {
this.$auth
.loginWith("laravelSanctum", {
data: this.form
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
}
};
</script>
Layout default
<template>
<div>
<div>
<b-navbar type="dark" variant="dark">
<b-navbar-brand href="/">NavBar</b-navbar-brand>
<b-navbar-nav class="ml-auto">
<template v-if="$auth.loggedIn">
<b-nav-item to="/dashboard">Dashboard</b-nav-item>
<b-nav-item href="#" #click.prevent="logout()">Logout</b-nav-item>
</template>
<template v-else>
<b-nav-item to="/login">Login</b-nav-item>
</template>
</b-navbar-nav>
</b-navbar>
</div>
<Nuxt />
</div>
</template>
<script>
export default {
methods: {
async logout() {
try {
await this.$auth.logout();
} catch (error) {
console.log(error);
}
}
}
};
</script>
#nuxt/auth do have a middleware for the auth already, you don't need to do it yourself.
To benefit of it, you can add this to your nuxt.config.js file
router: {
middleware: ['auth'],
},
In any .vue file that you want to whitelist (aka if you do not want to check if loggedIn is true), you can use the auth key
<script>
export default {
auth: false, // will bypass the middleware's verification
}
</script>
Everywhere else, it will double check that you're logged in before proceeding. Otherwise, it will bring you to the login page that you've specified.

CSRF token mismatch when using nuxt/auth + Laravel Sanctum

CSRF token mismatch. error on register page when I try to login it was working good.
my register page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Register">
<b-button variant="primary" #click="register()">Register</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
auth: 'guest',
data() {
return {
name: "john",
email: "john#email.com",
password: "123321"
};
},
methods: {
async register() {
const data = {
'name': this.name,
'email': this.email,
'password': this.password
}
console.log(data);
try {
const res = await this.$axios.post('/register', data)
console.log(res)
}
catch(e) {
console.log(e.message)
}
}
}
};
</script>
nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'hello',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
router: {
middleware: ['auth'],
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
],
axios: {
baseURL: "http://localhost:8000/api"
},
auth: {
strategies: {
'laravelSanctum': {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
endpoints: {
login: {
url: "/api/login"
},
logout: {
url: "/api/logout"
},
user: {
url: "/api/user"
}
},
user: {
property: false
}
}
},
redirect: {
login: "/login",
logout: "/",
home: "/dashboard"
}
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
babel: {
plugins: [
['#babel/plugin-proposal-private-methods', { loose: true }]
]
}
}
}
Login Page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Login">
<b-button variant="primary" #click="login()">Login</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
middleware: ["guest"],
data() {
return {
form: {
email : "john#email.com",
password : "123321"
}
};
},
methods: {
login() {
this.$auth
.loginWith("laravelSanctum", {
data: this.form
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
}
};
</script>
EDIT: I do have the following error in my network tab devtools.
network tab error xhr.js?b50d:177 POST localhost:8000/api/register 419 (unknown status) "message": "CSRF token mismatch.", "exception": "Symfony\Component\HttpKernel\Exception\HttpException",

How to pass data from a child component to the parent component using Laravel and Vue

I am using Vue.js 2 and Laravel 7.
I want to pass some errors from the child component to the parent controller. But for some reasons emit did not work.
This is the method of the child component AllocateTask:
methods: {
assignTask: function() {
this.form.task_id = this.user.tasks;
this.form.user_id = this.dev.id;
alert(this.form.task_id);
alert(this.form.user_id);
axios.post('/ticketsapp/public/api/store_task_user', this.form)
.then((response) => {
console.log(response.data);
alert('ok');
this.errors = response.data;
alert(Object.keys(this.errors).length);
if (Object.keys(this.errors).length === 0) {
alert('viva');
} else {
alert('noviva');
this.$emit('failure');
this.$emit('pass-errors', this.errors);
}
})
.catch(error => {
alert('no ok');
console.log(error);
});
}
}
This is the parent component TheReporterTickets:
<template>
<div>
<allocate-task :dev="dev" :tasks="tasks" #pass-errors="onPassErrors" #failure="displayErrors=true" #success="displaySuccess=true"></allocate-task>
<hr>
<validated-errors :errorsForm="errorsTicket" v-if="displayErrors===true"></validated-errors>
</div> </template>
<script>
import AllocateTask from "./AllocateTask.vue"
import ValidatedErrors from "./ValidatedErrors.vue"
export default {
components: {
'allocate-task': AllocateTask,
'validated-errors': ValidatedErrors
},
props: {
dev: {
type: Array,
required: true,
default: () => [],
},
tasks: {
type: Array,
required: true,
default: () => [],
}
},
mounted() {
console.log('Component mounted.');
},
data: function() {
return {
displayErrors: false,
errorsTicket: []
}
},
methods: {
onPassErrors(value) {
alert('error');
console.log('errors passed');
const values = Object.values(value);
this.errorsTicket = values;
console.log(this.errorsTicket);
}
}
} </script>
As you can imagine, I am unable to call the method onPassErrors located in the parent component. I visualize correctly the alert in the else statement of the child component, so I suppose that I am unable to pass the data from the child to the parent component.
Can help?

Vue: event emitted is not getting picked up

I am able to pick up fire emitgetcartitems but for some reason the other listener, emitaddnotes, is not firing handleAddNotes(). I checked in context of the component as well by checking this.$listeners and I only saw emitgetcartitems listed for it. I'm not sure why the other event is not working at all.
blade template
<div id = "app">
<Modal
:modal-type="modalType"
:selected-product="selectedProduct"
:variant-data="variantData"
#emitgetcartitems="handleGetCartItems"
#emitaddnotes="handleAddNotes"
>
</Modal>
<Cart>
</Cart>
</div>
app.js
window.Vue = require('vue');
window.axios = require('axios');
Vue.component('Modal',
require('./components/Modal.vue').default);
new Vue({
el: "#app",
data() {
return {
modalType: null,
orderNotes: null,
couponCode: null,
selectedProduct: {},
variantData: [],
cart: {}
}
},
methods: {
handleChangeTab: function(tab) {
this.activeTab = tab
},
handleHideFlashMsg: function() {
this.flashStatus = false
},
handleAddNotes: function(){
console.log("!!!!!!!")
},
handleGetCartItems: function() {
axios
.get('/api/a-cart')
.then(response => {
this.cart = response.cart;
});
},
}
)}
Modal.vue
<template>
<div>
<button v-on:click="addNotes()"></button>
</div>
</template>
<script>
export default {
data() {
return {
couponInput: '',
}
},
props: {
selectedProduct: {type: Object},
orderNotes: {type: String},
couponCode: {type: String}
},
methods: {
getCartItems: function() {
console.log("GET CART")
this.$emit('emitgetcartitems')
},
addNotes: function() {
console.log("ADD NOTES")
this.$emit('emitaddnotes')
},
}
}
</script>

Resources