I am making registration form in nuxt js, it takes data from api, I have installed axios and auth module, I wrote base url in nuxt.config.js file. It shows TypeError: Cannot read property 'post' of undefined
```template>
<div>
<section class="content">
<div class="register_form m-auto text-center form-group">
<form method="post" #submit.prevent="register" >
<h1 class ="register_title">REGISTER</h1>
<h2 class="register_text">PLEASE REGISTER TO USE THIS WEBSITE</h2>
<input class="form-control" type="text" placeholder = 'USERNAME' v-model="username" name="username" required>
<input class="form-control" type="password" placeholder = 'PASSWORD' v-model="password" name="password" required>
<button type="submit" to="#" class="register_btn">
REGISTER
</button>
</form>
</div>
</section>
</div>
</template>
<script>
export default {
layout: 'loginLayout',
data(){
return {
username: '',
password: ''
}
},
methods: {
async register() {
try {
await this.$axios.post('register', {
username: this.username,
password: this.password
})
this.$router.push('/')
}
catch (e) {
console.log(e)
}
}
}
}
</script>```
try to use
await this.$axios.$post instead of await this.$axios.$post
Related
My application shows a window where player can enter name and passcode to enter
When the player exists and has a card, I want to show the card as well.
When the player exists, I make the card visible. Then in 'created'I call fetchSpelerCards. This is successful but shows in the VUE console as pending...
I hope some experienced vue user reads this and can help me with a hint, reference or explanation.
For that I have in the following code:
<h2>Meld je aan</h2>
<form #submit.prevent="register" class="mb-3">
<div class="form-group">
<input type="text" class="form-control m-2" placeholder="naam" v-model="name">
</div>
<div class="form-group">
<input type="text" class="form-control m-2" placeholder="kies inlogcode" v-model="pass_code">
</div>
<button type="submit" #click="checkSpeler()" class="btn btn-primary btn-block" style="color:white">Save</button>
</form>
<p class="alert alert-danger" v-if="errorMessage !== ''"> {{errorMessage}} </p>
<p class="alert alert-success" v-if="successMessage !== ''"> {{successMessage}} </p>
<CardsSpeler v-if="spelerCorrect"></CardsSpeler>
</div>
</template>
The component looks as follows:
<h2>Cards 1</h2>
<form #submit.prevent="addCard" class="mb-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="title" v-model="card.title">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="description" v-model="card.description">
</textarea>
</div>
<div>
<input type="file" v-on:change="onFileChange" ref="fileUpload" id="file_picture_input">
</div>
<button type="submit" class="btn btn-primary btn-block" style="color:white">Save</button>
</form>
<div class="card card-body mb-2" v-for="card in cards" v-bind:key="card.id">
<h3> {{currentSpelerCard.title}} </h3>
<p> {{currentSpelerCard.description}}</p>
<img class="img-circle" style="width:150px" v-bind:src="currentSpelerCard.picture" alt="Card Image">
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
mounted(){
console.log('component mounted');
},
computed: {
...mapState([
'currentSpeler' ,'currentSpelerCard'
]),
},
data() {
return{
cardExists:false,
successMessage:'',
errorMessage:'',
}
},
created(){
this.fetchSpelerCards();
},
methods: {
...mapActions([ 'getGames', 'addGame', 'fetchSpelerCards' ]),
fetchSpelerCards(){
this.$store.dispatch('fetchSpelerCards', this.currentSpeler.speler.id )
.then(res => {
this.cardExists = true;
this.successMessage = res;
console.log(res);
})
.catch(err => {
this.errorMessage = err;
this.cardExists = false;
});
},
The corresponding action, in actions.js is:
export const fetchSpelerCards = ({commit}, speler_id) => {
return new Promise((resolve, reject) => {
let status = '';
let data ={};
fetch(`api/cardsBySpeler/${speler_id}`)
.then(res => {
status = res.status;
data = res.json();
})
.then(res=>{
if ( status === 200) {
commit('SET_PLAYER_CARD', data);
resolve('Kaart gevonden');
}
else {
reject('Er is geen kaart beschikbaar')
}
});
})
}
In the vuex-store I see (viewed with VUE add-on of chrome browser):
currentSpelerCard: Promise
Yet, the response of the fetch command was successful, and the card was pulled in, as I see also in the console: status 200, I can see name, title, image address etc..
I was under the assumption that, when the promise eventually resolves, the store is updated and the card becomes available because of the:
computed: { ...mapState([ 'currentSpeler' ,'currentSpelerCard' ]),
Can anyone help me and explain what I am doing wrong?
fetchSpelerCards in Vuex commits SET_PLAYER_CARD with data, this will be a pending promise. You need to await the promise.
You can solve this in a few different ways.
Making the function async and await res.json() would be the easiest.
...
fetch(`api/cardsBySpeler/${speler_id}`)
.then(async res => {
status = res.status;
data = await res.json();
})
...
I developed one page which is responsible for Registering the users previously i submitted the form without radio buttons, now i need to add radio buttons based on checked type button that value should be sent to the backend ,i am unable to figure out where did i mistaken please help me to fix this issue
Register.vue
<template>
<div class="main">
<div v-if="flag==true" class="container">
<img id="side-img" src="../assets/sideImg.png" alt="notFound" />
<p id="side-content">Online Book Shopping</p>
<div class="box">
<div class="headings">
<h5 class="signin" v-on:click="flip();" id="login" :class="{ active: isLogin }" #click="isLogin = true">Login</h5>
<h5 class="signup" id="signup" :class="{ active: !isLogin }" #click="isLogin = false">signup</h5>
</div>
<form ref="myForm" #submit.prevent="handlesubmit">
<div class="fullname">
<p>FullName</p>
<input type="name" id="name-input" class="namebox" required v-model="fullName" autocomplete="off" pattern="[A-Za-z]{3,12}">
</div>
<div class="username">
<p>EmailID</p>
<input type="email" id="Email-input" class="emailbox" autocomplete="off" required v-model="email" pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="password-section">
<p>Password</p>
<input :type="password_type" class="password" :class="{'password-visible': isPasswordVisible }" id="passField" v-model="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,}$" required>
<i class="bi bi-eye-slash" id="togglePassword" #click="togglePassword();"></i>
</div>
<div class="mobile">
<p>MobileNumber</p>
<input type="tel" class="telephone" autocomplete="off" v-model="mobile" id="tel" pattern="^\d{10}$" required>
</div>
<div class="role-btns">
<input type="radio" id="user" value="user" name="role" v-model="roleUser" >
<label for="user" class="radio-label">user</label>
<input type="radio" id="admin" value="admin" name="role" v-model="roleUser">
<label for="admin">admin</label>
</div>
<button class="btn-section" id="btn" type="submit">Signup</button>
</form>
</div>
</div>
<Login v-if="flag==false" />
</div>
</template>
<script>
import service from '../service/User'
export default {
name: 'Register',
components: {
Login: () => import('./Login.vue')
},
data() {
return {
fullName: '',
email: '',
password: '',
mobile: '',
roleUser:'',
password_type: "password",
isLogin: false,
isPasswordVisible: false,
flag: true,
title: 'Online Book Shopping'
}
},
methods: {
flip() {
this.flag = !this.flag;
},
togglePassword() {
this.password_type = this.password_type === 'password' ? 'text' : 'password'
this.isPasswordVisible = !this.isPasswordVisible
},
handlesubmit() {
let userData = {
fullName: this.fullName,
email: this.email,
password: this.password,
mobile: this.mobile
}
service.userRegister(userData).then(response => {
if (response.status == 201) {
alert("user registered successfully");
this.$refs.myForm.reset();
this.$router.push('/login');
}
return response;
}).catch(error => {
alert("invalid credentials");
return error;
})
}
}
}
</script>
<style lang="scss" scoped>
#import "#/styles/Register.scss";
</style>
let userData = {
fullName: this.fullName,
email: this.email,
password: this.password,
mobile: this.mobile,
roleUser:this.roleUser
}
this is the template I want to make a password input and checkbox while box is checked I want to type inside input to turn into the text instead of password
<!--template-->
<template>
<div>
<div id="login">
<h1 style="font-size:30px; color:black;">Login</h1>
<input type="text" placeholder="Username...">
<input :type="inputtype" placeholder="Password...">
<input type="checkbox" name="" id="" :checked="totext">
<button class="button is-link">Submit</button>
Register
Forgot the password..?!
</div>
</div>
</template>
17:5 error Unexpected labeled statement no-labels
17:16 error Expected an assignment or function call and instead saw an expression
<script>
export default {
data () {
inputtype: 'password'
},
methods: {
totext () {
this.inputtype = this.inputtype === 'password' ? 'text' : 'password'
}
}
}
</script>
Please try this code instead:
:type="totext ? 'password': 'text' "
<template>
<div>
<div id="login">
<h1 style="font-size:30px; color:black;">Login</h1>
<input type="text" placeholder="Username...">
<input :type="totext ? 'password': 'text' " placeholder="Password...">
<input type="checkbox" name="" id="" :checked="totext">
<button class="button is-link">Submit</button>
Register
Forgot the password..?!
</div>
</div>
</template>
And this script:
<script>
export default {
data () {
return {
totext : false
}
}
}
</script>
Or this one (the better one)
<template>
<div>
<div id="login">
<h1 style="font-size:30px; color:black;">Login</h1>
<input type="text" placeholder="Username...">
<input :type="isText" placeholder="Password...">
<input type="checkbox" name="" id="" :checked="totext">
<button class="button is-link">Submit</button>
Register
Forgot the password..?!
</div>
</div>
</template>
And
<script>
export default {
data () {
return {
totext : false
}
},
computed: {
isText(){
return totext ? 'password': 'text'
}
}
}
</script>
Please try this code :
data: () => ({
inputtype: 'password'
)}
You've merged the two sets of braces.
This:
data () {
inputtype: 'password'
},
should be this:
data () {
return {
inputtype: 'password'
}
},
I have a project that needs to be tested via Cypress. I am new in "Cypressing" by the way..
I have problem to find a solution about role-based testing where something like this happen:
If the xhr response gave a user data with role admin, it will redirect to dashboard/admin. Otherwise, if the xhr response gave a user data a role user, it will redirect to dashboard/user.
After that, each views may have different actions & behavior regarding to what kind of user who has logged in.
Please have a look at my script:
const BASE_URL = Cypress.env('BASE_URL')
const APP_NAME = Cypress.env('APP_NAME')
const AUTH_ID = Cypress.env('AUTH_ID')
const PASSWORD = Cypress.env('PASSWORD')
describe('Login Test', () => {
it('can perform a login action', () => {
cy.visit(BASE_URL)
cy.contains(APP_NAME)
cy.get('input[name="contact"]')
.type(AUTH_ID)
.should('have.value', AUTH_ID)
cy.get('input[name="password"]')
.type(PASSWORD)
.should('have.value', PASSWORD)
cy.get('#submit-button').click()
cy.url().should('contain', 'dashboard')
})
})
and please have a look at my Vue.js script too:
<template>
<div id="login">
<div class="login-card p-4">
<h1 class="text-center font-weight-bold text-primary py-5">STTKD</h1>
<!-- phone number input -->
<div class="form-group">
<label for="contact">Nomor Telepon</label>
<input
name="contact"
type="number"
class="form-control"
min="0"
placeholder="08xxx atau 628xxxx"
v-model="user.contact"
/>
</div>
<!-- password-input -->
<div class="form-group">
<label for="password">Password</label>
<input
name="password"
type="password"
class="form-control"
placeholder="Masukkan password"
v-model="user.password"
/>
</div>
<div class="form-group text-right">
Forgot password?
</div>
<!-- login-button -->
<div class="form-group">
<button
id="submit-button"
type="button"
class="btn btn-primary btn-block"
#click="onSubmit"
>LOGIN</button>
</div>
<div class="form-group text-center">
<p class="mb-0">
Don't have account?
<router-link :to="{ name: 'register' }" class="text-primary">Create a new one!</router-link>
</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
user: {
contact: "",
password: ""
}
};
},
methods: {
onSubmit() {
axios
.post("auth/login", this.user)
.then(resp => {
VueCookies.set("access_token", resp.data.access_token);
VueCookies.set("token_type", resp.data.token_type);
VueCookies.set("expires_at", resp.data.expires_at);
// redirect with" user" param if the roles array from the response includes "user"
if (resp.data.user.roles.includes("user")) {
this.$router.replace({
name: "dashboard",
params: {
role: "user"
}
});
return;
}
// else, redirect with "admin" param
this.$router.replace({
name: "dashboard",
params: {
role: "admin"
}
});
})
.catch(err => console.error(err));
}
}
};
</script>
As you see above, its running without problem but I have no idea about what to do next because the user behavior is kindof dynamic.
Please help me to solve this problem, any references are good for me if there is.
Thanks in advance.
I have a perfectly working form I can insert data into database using axios after form validation. I am just struggling to show a success message after inserting the data into the database. how to hide the form and display a succcess message in the same section after sending the data into the database??
here's my perfectly working code
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<div>
<form #submit.prevent="submit">
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx number">TRX No</label>
<input
type="text"
name="trx Number"
v-model="newUser.trx"
class="form-control trx-address-nooverflow"
placeholder="Copy paste your TRX no"
/>
<b-form-text id="input-formatter-help">
<a class="text-success">Your TRX address: {{trxNo}}</a>
</b-form-text>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
type="text"
name="name"
v-model="newUser.name"
class="form-control"
placeholder="Enter you name"
/>
</div>
<div class="form-group col-md-3">
<label for="email">Email</label>
<input
type="text"
name="email"
v-model="newUser.email"
class="form-control"
placeholder="Enter valid email address"
/>
</div>
<div class="form-group col-md-3">
<label for="country">Country</label>
<country-select
id="Country"
v-model="newUser.country"
:country="newUser.country"
topCountry="US"
class="form-control"
/>
</div>
<div class="form-group col-md-3">
<label for="mobile">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="newUser.mobile_no"
type="text"
placeholder="Enter your mobile no."
/>
<b-form-text id="input-formatter-help">
Please enter valid phone number
</b-form-text>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
</div>
</div>
</div>
</form>
</div>
</div>
</b-container>
</template>
here's my vue js code
<script>
import axios from 'axios'
export default{
data(){
return{
errorMessage: "",
successMessage: "",
text: "success",
errors: [],
users: [],
newUser: {trx: "", name: "", country: "", email: "", mobile_no: ""}
}
},
computed: {
trxNo: function() {
return this.$store.state.myAddress;
}
},
mounted: function(){
this.getAllUsers();
},
methods:{
getAllUsers: function(){
axios.get('https://onex.tronpayer.com/api/update-info-form.php?action=read', { crossdomain: true })
.then((response) => {
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.users = response.data.users;
}
});
},
submit(){
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('https://onex.tronpayer.com/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx: "", name: "", country: "", email: "", mobile_no: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
}
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
if (!this.newUser.trx) {
this.errors.push("Trx Number Required.");
}
if (!this.newUser.name) {
this.errors.push("Name Required.");
}
if (!this.newUser.country) {
this.errors.push("Country Required.");
}
if (!this.newUser.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.newUser.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.newUser.mobile_no) {
this.errors.push("Mobile Number Required.");
}
if (!this.errors.length) {
return true;
}
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
You can use the v-if conditional rendering for disabling the form and showing the message.
https://v2.vuejs.org/v2/guide/conditional.html
Just create a variable like savingSuccessful: false and set it to true when your ajax request was successful.
Use it now in your form like
<form #submit.prevent="submit" v-if="!savingSuccessful">
This means your form will be displayed until your variable is true.
For a success-message you can create something like this:
<div class="success" v-if="savingSuccessful">
{{ this.text }}
</div>
Your message will be rendered when the variable is true.
Here a JSFiddle:
https://jsfiddle.net/MichelleFuchs/nydruxzw/2/