Submit form to Quip API with Axios - vue.js

I want to submit a form data to Quip's Create Document API using vue.js and axios. This is what I've tried so far:
Form:
<form #submit="saveToQuip" method="POST" action="./post-order.html">
<div class="row">
<div class="col-lg-6 col-md-6">
<div class="row">
<div class="col-lg-12">
<div class="checkout__input">
<label>Receiver's Name<span>*</span></label>
<input type="text" name="First Name" v-model="fullname" required>
</div>
</div>
</div>
.....
</form>
JS:
new Vue({
el: '#submit-order',
data () {
return {
cartItems: [],
fullname: '',
facebookname: '',
email: 'NONE',
address: '',
phone_number: '',
payment_method: '',
delivery_dtime: '',
ordernotes: 'NONE'
}
},
methods:{
saveToQuip(submitEvent) {
......
axios.post('where-to-send-form-data', {
headers : {
Authorization: 'Bearer ' + personal_token,
'Content-Type': content_type
//Access-Control-Allow-Origin : *
},
params: {
title: this.fullname,
type: 'document',
member_ids: folder_id,
content: content
}
})
.then((response) => {
console.log(response)
})
.catch(function (error) {
console.log(error);
})
.then(function () {
}); ;
}
}
})
When I try to submit my form, it does not run the axios post command, and there is no error in the console. It just redirects the page to the next page. How do I achieve this?

Remove both method and action from your form and trigger the action from a button
<form #submit="saveToQuip" method="POST" action="./post-order.html">
to
<form>
...
<button #click="saveToQuip()">SAVE</button>

Related

Issue with nuxt/auth

For auth I do use nuxt-auth, when the login is successful, I want to redirect to the main page using this.$router.push('/'), then I get a response like blank page with the following message
2021
,
// for login
<template>
<div class="limiter">
<div
class="container-login100"
:style="{
backgroundImage: 'url(' + require(`#/assets/login/images/bg-01.jpg`) + ')',
}"
>
<div class="wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33">
<form class="login100-form validate-form flex-sb flex-w">
<span class="login100-form-title p-b-53"> Login Admin </span>
<a href="facebook.com" class="btn-face m-b-20">
<i class="fa fa-facebook-official"></i>
Facebook
</a>
<a href="google.com" class="btn-google m-b-20">
<img :src="require(`#/assets/login/images/icons/icon-google.png`)" alt="GOOGLE" />
Google
</a>
<div class="p-t-31 p-b-9">
<span class="txt1"> Email </span>
</div>
<div class="wrap-input100 validate-input" data-validate="Email is required">
<input v-model="auth.email" class="input100" type="email" name="email" />
<span class="focus-input100"></span>
</div>
<div class="p-t-13 p-b-9">
<span class="txt1"> Password </span>
Forgot?
</div>
<div class="wrap-input100 validate-input" data-validate="Password is required">
<input v-model="auth.password" class="input100" type="password" name="pass" />
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn m-t-17">
Login
</div>
<div class="w-full text-center p-t-55">
<span class="txt2"> Not a member? </span>
Register now
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
auth: false,
data() {
return {
auth: {
email: null,
password: null,
},
}
},
mounted() {
if (this.$auth.loggedIn) {
this.$router.push('/')
}
},
methods: {
async submit() {
try {
const response = await this.$auth.loginWith('local', { data: this.auth })
this.$router.push('/')
} catch (err) {
console.log(err)
}
},
},
}
</script>
store vuex index.js
export const getters = {
isAuthenticated(state) {
return state.auth.loggedIn
},
loggedInUser(state) {
return state.auth.user
}}
}
layout default.vue
<template>
<div class="wrapper">
<Sidebar v-if="isAuthenticated" />
<div :class="isAuthenticated ? 'main-panel' : ''">
<Navbar v-if="isAuthenticated" />
<Nuxt />
<Footer v-if="isAuthenticated" />
</div>
</div>
</template>
<script>
import Sidebar from '#/components/layout/Sidebar.vue'
import Navbar from '#/components/layout/Navbar.vue'
import Footer from '#/components/layout/Footer.vue'
import { mapGetters } from 'vuex'
export default {
components: { Sidebar, Navbar, Footer },
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser']),
},
}
</script>
// auth nuxt config
auth : {
strategies: {
local: {
token: {
property: 'token',
required: true,
type: 'Bearer'
},
user: {
property: 'user',
autoFetch: true
},
endpoints: {
login: { url: '/sign/login', method: 'post' },
logout: { url: '/sign/logout', method: 'post' },
user: { url: '/sign/user-login', method: 'get' }
}
}
}
}
base index ('/')
<template>
<div class="container">
<div>
<Logo />
<h1 class="title">Learn Nuxt</h1>
<div class="links">
<a href="https://nuxtjs.org/" target="_blank" rel="noopener noreferrer" class="button--green">
Documentation
</a>
<a
href="https://github.com/nuxt/nuxt.js"
target="_blank"
rel="noopener noreferrer"
class="button--grey"
>
GitHub
</a>
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser']),
},
}
</script>
In your vuex store, the state parameter in your getter only has access to local state. You can't access the auth state the way you tried.
In a vuex module, a getter gets 4 arguments, namely local state, local getters, root state and root getters. So if you would rewrite your getters like this it would probably work:
export const getters = {
isAuthenticated(state, getters, rootState) {
return rootState.auth.loggedIn
},
loggedInUser(state, getters, rootState) {
return rootState.auth.user
}}
}
But I still think it is a bit redundant doing it like that. I would replace isAuthenticated with this.$auth.loggedIn in your default layout. The nuxt-auth module globally injects the $auth instance, meaning that you can access it anywhere using this.$auth.
I had same problem after authorizing user and redirect user to the home page.
After many tries and doing many works, the right config of auth in nuxt.config.js seemed like this:
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
tokenType: false,
maxAge: 60 * 60
},
refreshToken: {
property: 'refresh_token',
data: '',
maxAge: 60 * 60
},
endpoints: {
login: {
url: 'url/of/token',
method: 'urlMethod'
},
refresh: {
url: 'url/of/refreshToken',
method: 'urlMethod'
},
logout: false,
user: false
}
}
},
cookie: false,
redirect: {
login: '/login/page',
logout: '/login/page',
callback: false,
home: '/home/page'
}
},
Note that I didn't have any refreshToken property, but I should set it as empty string in config to be able to work with nuxt/auth!
Hope I could help

Vue JS: Forms are not getting cleared when router.push() method is executed after the logout

I am using Flask as a backend and Vue JS as front end for my development. Vuex for state store.
In the logout() I am clearing the authentication token from localStorage via store.dispatch('/logout') and then using router.push('/login') to navigate to Login.vue. I find that the form details entered before are not getting cleared. When the logout() is performed it navigates to the Login.vue with flash message stating 'You have been logged out successfully'.
Below is the code snippet for the same:
logout() {
axios.get(`${this.host}:5000/logout`)
.then((res) => {
this.$store.dispatch('logout')
.then(() => {
this.$router.push('/login');
});
this.flashMessage.success({
message: res.data.msg,
time: 5000,
flashMessageStyle: {
backgroundColor: 'linear-gradient(#e66465, #9198e5)',
},
});
})
.catch((error) => {
this.flashMessage.error({
message: error.toString(),
time: 5000,
flashMessageStyle: {
backgroundColor: 'linear-gradient(#e66465, #9198e5)',
},
});
});
}
logout() is written in App.vue. Here router is an instance of vue-router.
To avoid the issue of form data not being cleared I have used router.go() instead of router.push() in the above code. But because of this implementation, the flash message is not getting displayed as the reload (because of router.go()) is overwriting the displaying of flash message which I don't want.
Please let me if it is possible to erase the form data after logout without getting into the trouble of not showing flash message.
Not sure how you have implemented Login.vue, but here is a Login.vue that I have implemented, and it works. One of the takeaways should be that my form model data values are initialized to empty strings.
<template>
<div id="login">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-md-offset-3 col-md-2 align-right">User Name</label>
<div class="col-md-3">
<input type="input" ref="username" class="form-control" id="username" v-model="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-offset-3 col-md-2 align-right">Password</label>
<div class="col-md-3">
<input type="password" class="form-control" id="password" v-model="password" v-on:keyup.enter="login">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-4">
<button type="button" class="btn btn-default"
v-on:click="login">Login</button>
<span class="error-msg" v-if="errorMsg">{{ errorMsg }}</span>
</div>
</div>
</form>
</div>
</template>
<script>
import { loginUrl, axios, processAjaxLoginError } from '../globalvars.js'
export default {
name: 'Login',
data() {
return {
username: '',
password: '',
errorMsg: ''
}
},
methods: {
login() {
axios.post(loginUrl, {
username: this.username,
password: this.password
})
.then(response => {
// Commit the token to the store
this.$store.commit('updateToken', { token: response.data.message });
// Clear error message
this.errorMsg = '';
// Redirect to customer index view
this.$router.push("/customers")
})
.catch(error => {
this.errorMsg = processAjaxLoginError(error);
})
}
},
computed: {
token() {
return this.$store.state.token;
}
},
mounted() {
this.$refs.username.focus();
}
}
</script>

Using SendGrid with Nuxt.js

This post is not a question actually.
More like help to the world for people who are struggling with Nuxt.js and SendGrid.
I've been using stackoverflow for such a long time so maybe now it's my turn to start helping others.
I've been working on Nuxt.js WebApp development for the past 8 weeks.
Nuxt.js is a massive learning curve and challenge for me but I really love working with this technology.
I spent the last 2 days developing sending the form with the use of SendGrid. There's not too much help online and I've been struggling a lot but I made it!
So maybe some people will find my post useful.
Here's my form:
<form
v-show="!isSubmitted"
class="contact-us__form"
#submit.prevent="validate">
<b-form-group :class="{'form-group--error': $v.name.$error}">
<b-form-input
id="name"
v-model.trim="$v.name.$model"
type="text"
placeholder="Full Name">
></b-form-input>
<div class="error" v-if="!$v.name.required">Field is required</div>
<div class="error" v-if="!$v.name.minLength">Name must have at least {{$v.name.$params.minLength.min}} letters.</div>
</b-form-group>
<b-form-group :class="{'form-group--error': $v.phone.$error}">
<b-form-input
id="phone"
v-model.trim="$v.phone.$model"
type="number"
placeholder="Phone Number">
></b-form-input>
<div class="error" v-if="!$v.phone.required">Field is required</div>
</b-form-group>
<b-form-group :class="{'form-group--error': $v.email.$error}">
<b-form-input
id="email"
v-model.trim="$v.email.$model"
type="email"
placeholder="Email Address">
></b-form-input>
<div class="error" v-if="!$v.email.required">Field is required</div>
</b-form-group>
<div class="d-flex align-items-end">
<b-form-group :class="{'form-group--error': $v.message.$error}">
<b-form-textarea
id="message"
v-model.trim="$v.message.$model"
type="text"
placeholder="Message"
></b-form-textarea>
<div class="error" v-if="!$v.message.required">Field is required</div>
<div class="error" v-if="!$v.message.minLength">Name must have at least {{$v.message.$params.minLength.min}} characters.</div>
</b-form-group>
<b-form-group>
<b-button
type="submit"
variant="secondary"
v-html="'S'"
:disabled="submitting" />
</b-form-group>
</div>
</form>
script:
export default {
mixins: [validationMixin],
components: {
subscribeBox
},
data() {
return {
map: bgMap,
name: "",
phone: "",
email: "",
message: "",
submitting: false,
isSubmitted: false,
error: false,
}
},
validations: {
name: {
required,
minLength: minLength(4)
},
phone: {
required,
},
email: {
required,
email
},
message: {
required,
minLength: minLength(5)
}
},
methods: {
validate() {
if (this.$v.$invalid || this.$v.$error|| this.submitting) {
this.$v.$touch();
return
}
this.onSsubmit();
},
async onSsubmit() {
this.submitting = true;
this.error = false;
try {
await this.$axios.$post('/api/v1/send-email', {
name: this.name,
phone: this.phone,
email: this.email,
message: this.message,
});
this.submitting = false
this.isSubmitted = true
await new Promise(resolve => setTimeout(resolve, 2500))
} catch(e) {
this.submitting = false
this.error = true
console.error(e)
}
},
},
}
nuxt.config.js
serverMiddleware: ['~/api/v1/send-email.js'],
api/v1/send-email.js (all the API Keys are placed in .env file)
const express = require("express");
const bodyParser = require('body-parser')
const sgMail = require('#sendgrid/mail');
const app = express();
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
app.use(bodyParser.json())
app.post("/", (req, res) => {
let msg = {
to: req.body.email, // Change to your recipient
from: '', // Change to your verified sender
subject: 'Message from ' + req.body.name,
text: 'telephone ' + req.body.phone + ', ' + 'message ' + req.body.message,
}
sgMail
.send(msg)
.then(() => {
return res.status(200).json({ 'message': 'Email sent!' })
})
.catch((error) => {
return res.status(400).json({ 'error': 'Opsss... Something went wrong ' + error })
})
});
module.exports = {
path: "/api/v1/send-email",
handler: app
};
This app is still not finished but the code is working 100%!
I'm new to Nuxt.js so some bits may not look awesome but I'm also happy and open to feedback and suggestions.
Thank you for reading my post and good luck with your project! :)

problems with Vuex data rendering

I'm studying reactivity of vuex using nuxt and module mode of store. The problem is, that despite all data in store is changed by actions => mutations successfully, they do not appear on the page, and shows only empty new element of store array. here are my files:
store>contacts>index.js:
let initialData = [
{
id: 1,
name: 'Michael',
email: 'michael.s#mail.com',
message: 'message from Michael'
},
{
id: 2,
name: 'Mark',
email: 'mark.sh#email.com',
message: 'message from Mark'
},
{
id: 3,
name: 'Valery',
email: 'valery.sh#mail.com',
message: 'message from Valery'
}
]
const state = () =>{
return {
contacts: []
}
}
const getters = {
allContacts (state) {
return state.contacts
}
}
const actions = {
async initializeData({ commit }) {
commit('setData', initialData)
},
addNewContact({ commit, state }, newContact) {
commit('addContact', newContact)
}
}
const mutations = {
setData: (state, contacts) => (state.contacts = contacts),
addContact: (state, newContact) => state.contacts.push(newContact)
}
export default { state, getters, mutations, actions}
component itself:
<template>
<div class="contact-form">
<div class="links">
<nuxt-link to="/">home</nuxt-link>
<nuxt-link to="/contact-form">contact form</nuxt-link>
</div>
<h1>leave your contacts and message here:</h1>
<div class="input-wrapper">
<form class="feedback-form" action="">
<div class="name">
<label for="recipient-name" class="col-form-label">Ваше имя:</label>
<input type="text" id="recipient-name" v-model="obj.userName" name="name" class="form-control" placeholder="Представьтесь, пожалуйста">
</div>
<div class="form-group">
<label for="recipient-mail" class="col-form-label">Ваш email:</label>
<input type="email" v-model="obj.userEmail" name="email" id="recipient-mail" class="form-control" placeholder="example#mail.ru">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Сообщение:</label>
<textarea name="message" v-model="obj.userMessage" id="message-text" class="form-control"></textarea>
</div>
<button #click.prevent="addToStore()" type="submit">submit</button>
</form>
</div>
<h3>list of contacts</h3>
<div class="contacts-list">
<div class="list-element" v-for="contact in allContacts" :key="contact.id">
id: {{contact.id}} <br> name: {{contact.name}}<br/> email: {{contact.email}}<br/> message: {{contact.message}}
</div>
</div>
</div>
</template>
<script>
import { mapMutations, mapGetters, mapActions } from 'vuex'
export default {
data() {
return {
obj: {
userName: '',
userEmail: '',
userMessage: ''
}
}
},
mounted() {
console.log(this.showGetters)
},
created() {
this.initializeData()
},
methods: {
...mapActions({
initializeData: 'contacts/initializeData',
addNewContact: 'contacts/addNewContact'
}),
addToStore() {
this.addNewContact(this.obj)
},
},
computed: {
...mapGetters({
allContacts: 'contacts/allContacts',
}),
showGetters () {
return this.allContacts
}
},
}
</script>
so, could anybody help to understand, what is wrong?
You've got mismatched field names.
Inside obj you've called them userName, userEmail and userMessage. For all the other contacts you've called them name, email and message.
You can use different names if you want but somewhere you're going to have to map one onto the other so that they're all the same within the array.
You should be able to confirm this via the Vue Devtools. The first 3 contacts will have different fields from the newly added contact.

Vuejs and vue-qrcode-reader add beep scan

Hello I use the library view-qrcode-reader for QR Code scan. I try to add a BEEP scan but I do not feel that the library does this kind of thing. So I did the thing manually but it does not work either.
<template>
<div class="container" id="app">
<router-link class="waves-effect waves-light btn" to="/livreur"><i class="material-icons">arrow_back</i>
</router-link>
<div class="row center">
<span v-if="errors" class="card-panel white-text red darken-1"><strong>{{ errors }}</strong></span>
</div>
<div class="row infos">
<span v-if="infos" class="card-panel white-text green green-1"><strong>Email & SMS envoyé à {{ infos.firstname }} {{ infos.lastname }}</strong></span>
</div>
<br/>
<div class="row">
<qrcode-stream #decode="onDecode"></qrcode-stream>
</div>
</div>
</template>
<script>
var attributes = {
setting: {
soundSrc: '/sounds/beep.mp3'
}
}
export default {
name: 'prepa',
data () {
return {
infos: '',
errors: '',
success: ''
}
},
methods: {
onDecode (decodedString) {
var audio = new Audio(attributes.setting.soundSrc)
audio.play()
this.$http.get('/orders/delivery/prepa/' + decodedString, {headers: {Authorization: `Bearer ${localStorage.token}`}})
.then(request => this.trackingInfos(request))
.catch((request) => this.trackingFail(request))
},
trackingInfos (req) {
if (req.data.error) {
return this.trackingFail(req)
}
this.errors = ''
this.infos = req.data.datas
this.save()
},
trackingFail (req) {
if (req.data.error) {
this.errors = req.data.error
}
},
save () {
this.$http.post('/order_histories', {
location: this.infos.city,
status: '/api/order_statuses/' + this.$preparation,
User: '/api/users/' + localStorage.userId,
orderId: '/api/orders/' + this.infos.orderId,
headers: {Authorization: `Bearer ${localStorage.token}`}
})
.then(request => this.successPrepa(request))
.catch(() => this.failPrepa())
},
successPrepa (req) {
if (req.data.error) {
return this.failPrepa(req)
}
this.errors = ''
this.success = req.status
},
failPrepa (req) {
if (req.data.error) {
this.errors = req.data.error
}
}
}
}
</script>
No beep and an error that appears in the console.
:8080/sounds/beep.mp3:1 GET http://127.0.0.1:8080/sounds/beep.mp3 net::ERR_ABORTED 404 (Not Found)
:8080/#/prepa:1 Uncaught (in promise) DOMException
Thanks for your help.