Hello i want to POST request with Axios to my back-end's API on VueJS. But my POST request turn a OPTIONS request.What i do wrong to where? Can you help me? i will go crazy...
Signup.vue Code:
<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'
const fullName = ref('')
const username = ref('')
const email = ref('')
const password = ref('')
async function addUser() {
const response = await axios.post("http://localhost:3000/user/", {
fullName: fullName.value,
username: username.value,
email: email.value,
password: password.value
})
console.log(response)
}
</script>
<template>
<div class="">
<h1>Login</h1>
<br>
<label for="fullname">Name & Surname</label>
<input type="text" v-model="fullName" id="fullname" class="form-control " required autofocus placeholder="John Die" aria-label="Fullname" aria-describedby="basic-addon1">
<label for="username">Username</label>
<input type="text" v-model="username" id="username" class="form-control " required placeholder="john.die" aria-label="Username" aria-describedby="basic-addon1">
<label for="email">E-mail (optional)</label>
<span class="input-group-text" id="basic-addon1">#</span>
<input type="text" v-model="email" id="email" class="form-control" placeholder="johndie#example.com" aria-label="E-mail" aria-describedby="basic-addon1">
<label for="password">Password</label>
<input type="password" v-model="password" class="form-control" required placeholder="Password" id="password">
<button name="button" #click="addUser()" class="btn btn-success text-center input-group" >JOIN</button>
<br><br>
<p class="text-center">
Do you have an account?
<a id="login" href="/login" class="text-info">Login</a>
</p>
</div>
</template>
Related
Totally new to Vue.js. Here's my issue:-
<template>
<div class="login-page">
<transition name="fade">
<div v-if="!registerActive" class="wallpaper-login"></div>
</transition>
<div class="wallpaper-register"></div>
<div class="container">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-8 mx-auto">
<div v-if="!registerActive" class="card login" v-bind:class="{ error: emptyFields }">
<h1>Sign In</h1>
<form class="form-group">
<input v-model="emailLogin" type="email" class="form-control" placeholder="Email" required>
<input v-model="passwordLogin" type="password" class="form-control" placeholder="Password" required>
<input type="submit" class="btn btn-primary" #click="doLogin">
<p>Don't have an account? Sign up here
</p>
<p>Forgot your password?</p>
</form>
</div>
<div v-else class="card register" v-bind:class="{ error: emptyFields }">
<h1>Sign Up</h1>
<form class="form-group">
<input v-model="emailReg" type="email" class="form-control" placeholder="Email" required>
<input v-model="passwordReg" type="password" class="form-control" placeholder="Password" required>
<input v-model="confirmReg" type="password" class="form-control" placeholder="Confirm Password" required>
<input type="submit" class="btn btn-primary" #click="doRegister">
<p>Already have an account? Sign in here
</p>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
registerActive: false,
emailLogin: "",
passwordLogin: "",
emailReg: "",
passwordReg: "",
confirmReg: "",
emptyFields: false
};
},
methods: {
doLogin() {
if (this.emailLogin === "" || this.passwordLogin === "") {
this.emptyFields = true;
} else {
alert("You are now logged in");
}
},
doRegister() {
if (this.emailReg === "" || this.passwordReg === "" || this.confirmReg === "") {
this.emptyFields = true;
} else {
alert("You are now registered");
}
}
}
};
</script>
My intentions are to wire-up the above to an API like thus:-
http://127.0.0.1:8000/api/login
using either the fetch API or something similar. Currently, the form doesn't display in the browser and throws the above error..
Any advice would be great.
With this, my vue HTML finally loads.
Remove these:-
resources/views/layouts/app.blade.php
{{--<script src="https://unpkg.com/vue#3"></script>--}}
{{--<script src="https://unpkg.com/vue-router#4"></script>--}}
</body>
</html>
Add this to your main file:-
resources/js/app.js
import * as Vue from 'vue';
import * as VueRouter from 'vue-router';
npm run dev and voila! Thanks to: Murad for a very useful comment: Vue3 Presence of a css class on element in single file component causes rendering failure when added to dom, Invalid VNode type: Symbol()
I have multiple input from child component that I want to submit from parent component
Parent Component:
<EmployeesPersonalData
v-model:fn="fn"
v-model:ln="ln"
v-model:nik="nik"
/>
<div class="px-2 py-3 text-right sm:px-6">
<button type="submit" #click="signUp">Save</button>
</div>
<script setup>
import { ref, onMounted } from 'vue'
import EmployeesPersonalData from
'./Forms/EmployeesPersonalData.vue';
const auth = getAuth
const fn = ref('')
const ln = ref('')
const nik = ref('')
const email = ref('')
const password = ref('')
function signUp() {
console.log(email.value)
}</script>
EmployeesPersonalData:
<template>
<div>
<label for="first-name">First name</label>
<input id="first-name" :value="fn" #input="$emit('create:fn', $event.target.value)" type="text" autocomplete="first-name" required placeholder="First Name">
</div>
<div>
<label for="last-name">Last name</label>
<input id="last-name" :value="ln" #input="$emit('create:ln', $event.target.value)" type="text" autocomplete="last-name" required placeholder="Last Name">
<p>*Required</p>
</div>
<div>
<label for="ssn_nik">SSN/NIK</label>
<input id="ssn_nik" :value="nik" #input="$emit('create:nik', $event.target.value)" type="number" autocomplete="nik" required placeholder="SSN/NIK">
</div>
</div>
<script setup>
import { ref } from 'vue'
const props = defineProps({
fn : String,
ln : String,
nik : String,
})
But when I tried to console.log(email.value) or console.log(email) it message/return nothing.
Whats wrong with code that I write? thanks in advance
You should also define the emitted events which have this syntax update:property like:
<script setup>
import { ref } from 'vue'
const props = defineProps({
fn : String,
ln : String,
nik : String,
})
const emit=defineEmits(['update:fn','update:ln','update:nik'])
and in template replace create by update :
<template>
<div>
<label for="first-name">First name</label>
<input id="first-name" :value="fn" #input="$emit('update:fn', $event.target.value)" type="text" autocomplete="first-name" required placeholder="First Name">
</div>
<div>
<label for="last-name">Last name</label>
<input id="last-name" :value="ln" #input="$emit('update:ln', $event.target.value)" type="text" autocomplete="last-name" required placeholder="Last Name">
<p>*Required</p>
</div>
<div>
<label for="ssn_nik">SSN/NIK</label>
<input id="ssn_nik" :value="nik" #input="$emit('update:nik', $event.target.value)" type="number" autocomplete="nik" required placeholder="SSN/NIK">
</div>
</div>
I'm trying to display data I'm getting with an Axios request, when I log this.form in console it displays the data, but when I try to output the title with {{ form.title }} nothing shows. When look in Vue dev-tools 'form' isn't populated too. What am I missing?
My code:
<template>
<div class="newitem">
<h2>Bewerk {{ form.title }}</h2>
<form #submit.prevent="formSubmit">
<label for="name">Naam van de taak</label>
<input type="text" name="name" id="name" v-model="form.title">
<div class="date">
<div class="date__item allday">
<label for="allDay">Hele dag</label>
<input type="checkbox" name="allDay" id="allDay" v-model="form.allDay">
</div>
<div class="date__item">
<label for="date">Datum wanneer je begint</label>
<input type="date" name="date" id="date" v-model="form.date">
</div>
<div v-if="!this.form.allDay" class="date__item">
<label for="from">Tijd wanneer je begint</label>
<input type="time" name="from" id="from" v-model="form.from">
</div>
<div v-if="!this.form.allDay" class="date__item">
<label for="till">Tijd wanneer je denkt klaar te zijn</label>
<input type="time" name="till" id="till" v-model="form.till">
</div>
<div class="date__item">
<label for="date">Datum wanneer denkt klaar te zijn</label>
<input type="date" name="date" id="date" v-model="form.date">
</div>
</div>
<label for="type">Type</label>
<select name="type" id="type" v-model="form.type">
<option selected disabled>Kies een type</option>
<option>SO</option>
<option>Repetitie</option>
<option>Leerwerk</option>
<option>Maakwerk</option>
</select>
<label for="description">Wat ga je je maken/leren?</label>
<textarea id="description" v-model="form.description"></textarea>
<button class="button button-primary">Opslaan</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
form: [],
}
},
created() {
this.fetchPost();
},
methods: {
fetchPost() {
this.$eventBus.$on('send-data', (id) => {
axios.get('/agenda_items/' + id).then(response => {
this.form = response.data;
console.log(this.form)
})
.catch(error => console.log(error))
});
},
}
}
</script>
edit with v-for:
<template>
<div class="newitem">
<div class="newitem__inner" v-for="form in forms" :key="form.id">
<h2>Bewerk {{ form.title }}</h2>
<form #submit.prevent="formSubmit">
<label for="name">Naam van de taak</label>
<input type="text" name="name" id="name" v-model="form.title">
<div class="date">
<div class="date__item allday">
<label for="allDay">Hele dag</label>
<input type="checkbox" name="allDay" id="allDay" v-model="form.allDay">
</div>
<div class="date__item">
<label for="date">Datum wanneer je begint</label>
<input type="date" name="date" id="date" v-model="form.date">
</div>
<div v-if="!this.form.allDay" class="date__item">
<label for="from">Tijd wanneer je begint</label>
<input type="time" name="from" id="from" v-model="form.from">
</div>
<div v-if="!this.form.allDay" class="date__item">
<label for="till">Tijd wanneer je denkt klaar te zijn</label>
<input type="time" name="till" id="till" v-model="form.till">
</div>
<div class="date__item">
<label for="date">Datum wanneer denkt klaar te zijn</label>
<input type="date" name="date" id="date" v-model="form.date">
</div>
</div>
<label for="type">Type</label>
<select name="type" id="type" v-model="form.type">
<option selected disabled>Kies een type</option>
<option>SO</option>
<option>Repetitie</option>
<option>Leerwerk</option>
<option>Maakwerk</option>
</select>
<label for="description">Wat ga je je maken/leren?</label>
<textarea id="description" v-model="form.description"></textarea>
<button class="button button-primary">Opslaan</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
forms: [],
}
},
created() {
this.fetchPost();
},
methods: {
fetchPost() {
this.$eventBus.$on('send-data', (id) => {
axios.get('/agenda_items/' + id).then(response => {
this.forms = response.data;
console.log(this.forms)
})
.catch(error => console.log(error))
});
},
}
}
</script>
It seems the eventbus was the problem. I removed it, and got the id with this.$attrs.id;
fetchPost() {
var id = this.$attrs.id;
axios.get('/agenda_items/' + id).then(response => {
this.form = response.data[0];
})
.catch(error => console.log(error))
}
I am learning Vue.js I have successfully made this registration form and its working fine
but I'm having a problem in showing errors.
register.vue page
<form #submit.prevent="RegisterUser" aria-label="Register">
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
<div class="col-md-6">
<!-- <input id="name" v-model="name" type="text" class="form-control" name="name" value="" required autofocus> -->
<input type="text" v-model="name" class="form-control" required="required" autofocus="autofocus">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<!-- <input id="email" v-model="email" type="email" class="form-control" name="email" value="" required> -->
<input type="email" v-model="email" required autofocus class="form-control">
{{ errors.email }}
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<!-- <input id="password" v-model="password" type="password" class="form-control" required> -->
<input type="password" v-model="password" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<!-- <input id="password-confirm" v-model="password_confirmation" type="password" class="form-control" required> -->
<input type="password" v-model="confirm_password" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
This is my scripts in register.vue page working registration fine
<script>
export default {
// props: ['name'],
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: {},
};
},
methods: {
RegisterUser() {
axios.post('/register', {
name: this.name,
email: this.email,
password: this.password,
password_confirmation:this.confirm_password
})
.then(function(response){
swal({
title: "Good job!",
text: "Login Success",
icon: "success",
button: "Okay",
})
.then((willDelete) => {
if (willDelete) {
window.location.href = '/home';
}
});
})
.catch(function (error) {
console.log(error.response.data);
});
}
}
}
</script>
This is the Errors I want to fetch...
How to fetch and how this errors on my vue components?
Note!! This solution is based on ES6 so you might have to transpile this to ES5
I had this issue a while back so I wrote a simple class to help manage validation messages from the server. https://gist.github.com/nonsocode/e6f34a685f8be1422c425e3a20a69a4b
You can use it by importing this to your template
import ErrorBag from 'path-to-errorbag-class'
and use it in your data method like so
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: new ErrorBag,
};
},
In your template, you can check if there's a validation error and then decide how you ant to handle it. I'll assume you're using bootsrap 4
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="email" v-model="email" required autofocus :class="{'form-control': true, 'is-invalid': errors.has('email')}">
<div class="invalid-feedback" v-if="errors.has('email')" >{{ errors.first('email') }}</div>
</div>
</div>
in the catch method of your ajax request,
axios(...)
.then(...)
.catch(function (error) {
if (error.response && error.response.status == 422) {
const errors = err.response.data.errors;
this.errors.setErrors(errors);
}
});
After successfully submitting to your server, you can call the clearAll method on the errorbag to clear all errors from the bag
In my home page i have to create records and when i am creating the records and clicking on submit button and getting like added successfully. After that the created record is not available in the list records.When i'm creating another new record and submit it the previous created record is displays in the list.
Type Script code is:
import { Component, OnInit } from '#angular/core';
import {FormControl, Validators, NgForm } from '#angular/forms';
import { VisitService } from '../shared/visit.service';
import { ToastrService } from 'ngx-toastr';
import { Response, RequestOptions, Http, Headers } from '#angular/http';
import { CookieService } from 'ngx-cookie-service';
#Component({
selector: 'app-visit',
templateUrl: './visit.component.html',
styleUrls: ['./visit.component.css']
})
export class VisitComponent implements OnInit {
cookieValue = 'UNKNOWN';
constructor(private visitService: VisitService,private http: Http,private cookieService: CookieService, private toastr: ToastrService ) { }
ngOnInit() {
this.resetForm();
this.cookieValue = this.cookieService.get('session');
console.log('token from browser' + this.cookieValue );
const url = `http://localhost:8080//api/getallvisits/`;
// const headers = new Headers({'Content-Type': 'application/json','Authorization':'Bearer' +this.cookieValue});
let headers = new Headers({ 'Authorization': 'Bearer ' + this.cookieValue });
// const headers = new Headers();
// headers.append('Authorization', 'Bearer' +this.cookieValue );
const options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.subscribe(res => {
console.log('message from' + res);
// this.refresh();
alert('successfullyyy...');
// console.log('message from' + people.json())
});
}
resetForm(form?: NgForm) {
if (form != null)
form.reset();
this.visitService.selectedVisit = {
'ID':null,
'UserName': '',
'Height': null,
'Weight': null,
'Temperature': null,
'BloodPressure': '',
'PatientNote': '',
'NurseNote': '',
'DoctorNote': '',
}
}
onSubmit(form: NgForm) {
if (form.value.ID == null) {
this.visitService.createVisit(form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.success('New Record Added Succcessfully', 'Employee Register');
})
}
else {
this.visitService.updateVisit(form.value.ID, form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.info('Record Updated Successfully!', 'Employee Register');
});
}
}
}
And my HTML page is:
<form class="visit-form" #visitForm="ngForm" (ngSubmit)="onSubmit(visitForm)">
<input type="hidden" name="ID" #ID="ngModel" [(ngModel)]="visitService.selectedVisit.ID">
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="UserName" name="UserName" #UserName="ngModel" [(ngModel)]="visitService.selectedVisit.username"
placeholder="User Name" required>
<div class="validation-error" *ngIf="UserName.invalid && UserName.touched">This Field is Required.</div>
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Height" name="Height" #Height="ngModel" [(ngModel)]="visitService.selectedVisit.height" placeholder="Height"
required>
<div class="validation-error" *ngIf="Height.invalid && Height.touched">This Field is Required.</div>
</mat-form-field>
</div>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Temperature" name="Temperature" #Temperature="ngModel" [(ngModel)]="visitService.selectedVisit.temperature" placeholder="Temperature">
</mat-form-field>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Weight" name="Weight" #Weight="ngModel" [(ngModel)]="visitService.selectedVisit.weight" placeholder="Weight">
</mat-form-field>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Blood Pressure" name="BloodPressure" #BloodPressure="ngModel" [(ngModel)]="visitService.selectedVisit.bloodpressure" placeholder="Blood Pressure">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Patient Note" name="PatientNote" #PatientNote="ngModel" [(ngModel)]="visitService.selectedVisit.patientnote" placeholder="Patient Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Nurse Note" name="NurseNote" #NurseNote="ngModel" [(ngModel)]="visitService.selectedVisit.nursenote" placeholder="Nurse Note">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Doctor Note" name="DoctorNote" #DoctorNote="ngModel" [(ngModel)]="visitService.selectedVisit.doctornote" placeholder="Doctor Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!visitForm.valid" type="submit" class="btn btn-lg btn-block btn-info">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(visitForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
Anyone please refer that.Thank You
See if you are displaying the value in html table or like that then after submit you have to destroy the table .
and again Reinit the table then only it will display the current added value as well.
So You can do that or else call the onload function when submit function ends .
or if you have some other issue then let me know in details.