How can I Upload files and JSON data in the same request with AlpineJS - file-upload

I need to Add data & image file in a same post request using alpine js.

I think it is a little bit late. But, someone else might need take benefit from this answer in the future.
You can use Javascript's FormData to handle both data and file.
Bellow, I am copying a part from my application to show the full process of actually uploading image with Alpine JS and sending it as part of Form Data to your API end.
HTML Part:
<form method="post" enctype="multipart/form-data" #submit.prevent="$store.app.submitData()">
<div class="row mb-4">
<div class="form-group col-md-4">
<label>App Name</label>
<input type="text" name="name" class="form-control" x-model="$store.app.form.name">
</div>
<div class="form-group col-md-4">
<label>Slug</label>
<input type="text" name="name" class="form-control" x-model="$store.app.form.slug">
</div>
<div class="form-group col-md-4">
<label>Icon/Logo</label>
<input type="file" name="image_icon" class="form-control" x-on:change="$store.app.selectFile($event)" accept="image/png, image/jpg, image/jpeg">
</div>
</div>
<div class="row">
<div class="col-md-12 text-end mt-3">
<button type="submit" class="btn btn-lg btn-primary mb-5" :disabled="$store.app.loading">
<span class="indicator-label">Save</span>
</button>
</div>
</div>
</form>
Alpine JS Part:
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('app', {
loading: false,
form: {
name: '',
image_icon: '',
slug: ''
},
selectFile(event) {
this.form.image_icon = event.target.files[0]
},
submitData() {
//Create an instance of FormData
const data = new FormData()
let url = '/application'
// Append the form object data by mapping through them
Object.keys(this.form).map((key, index) => {
data.append(key, this. Form[key])
});
this.loading = true
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
body: data
})
.then(response => {
//...
})
.finally(() => {
this. Loading = false
});
}
})
})
</script>
Please note that I have used store in this example, you can use Alpine Data, function or inline x-data as you please.
Appending to the form data just requires a key and value pair, for example;
const data = new FormData();
data.append('name', 'John');
data.append('surname', 'Doe');
I hope this helps.

Related

how can I update a vue child-component from the vuex-store

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();
})
...

How can I create role based testing in Cypress?

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.

Method Updating Data Twice on Form Submission

I have a component that is a form that I input a name and it updates a value on a field on the backend based on which input the name is. Right now I have two inputs (host and scout) and they work fine if I just fill one input. My problem is, when I fill both inputs, the name on the host input will always get updated twice while the name on the scout field will work just fine. Not sure if I was clear enough.
Here is the code for the component so far
<template>
<div class="add-wave">
<h3>Add Wave</h3>
<div class="row">
<form #click.prevent="addwave()" class="col s12">
<div class="row">
<div class="input-field col s12">
<input type="text" v-model="host" />
<label class="active">Host</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" v-model="scout" />
<label class="active">Scout</label>
</div>
</div>
<button type="submit" class="btn">Submit</button>
<router-link to="/member" class="btn grey">Cancel</router-link>
</form>
</div>
</div>
</template>
<script>
import { db, fv } from "../data/firebaseInit";
export default {
data() {
return {
host: null,
scout: null
};
},
methods: {
addwave() {
this.addhost();
db.collection("members")
.where("name", "==", this.scout)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
doc.ref.update({
scout: fv.increment(1),
total: fv.increment(1)
});
});
});
},
addhost() {
db.collection("members")
.where("name", "==", this.host)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
doc.ref.update({
host: fv.increment(1),
total: fv.increment(1)
});
});
});
}
}
};
</script>
I'm not sure why is it updating twice only when I fill both input fields.

vue js get multiple values from inputs

So I have 2 blocks of HTML, each containing 2 input fields and when submitting the form, I want to get all values from the inputs, and then create an object from the values...
As of know I've done it with plain vanilla JS and it works as it should, however if feels like to touching the DOM a bit to much, and also are very much depending on a specific DOM struckture, and therefore I was thinking there must be a better way, the VUE way so to speak, however im a bit stuck on how to do this the VUE way, which is why posting the question here in hope of getting some useful tips :)
HTML:
<form novalidate autocomplete="off">
<div class="input-block-container">
<div class="input-block">
<input type="text" placeholder="Insert name" name="name[]" />
<input-effects></input-effects>
</div>
<div class="input-block">
<input type="email" placeholder="Insert email address" name="email[]" />
<input-effects></input-effects>
</div>
</div>
<div class="input-block-container">
<div class="input-block">
<input type="text" placeholder="Insert name" name="name[]" />
<input-effects></input-effects>
</div>
<div class="input-block">
<input type="email" placeholder="Insert email address" name="email[]" />
<input-effects></input-effects>
</div>
</div>
<button class="button button--primary" #click.prevent="sendInvites"><span>Send</span></button>
</form>
JS:
methods: {
createDataObject() {
let emailValues = document.querySelectorAll('input[type="email"]');
emailValues.forEach((email) => {
let name = email.parentNode.parentNode.querySelector('input[type="text"]').value;
if(email.value !== "" && name !== "") {
this.dataObj.push({
email: email.value,
name
});
}
});
return JSON.stringify(this.dataObj);
},
sendInvites() {
const objectToSend = this.createDataObject();
console.log(objectToSend);
//TODO: Methods to send data to server
}
}
You can provide data properties for each of your inputs if you have static content.
data: function() {
return {
name1: '',
email1: '',
name2: '',
email2: ''
}
}
Then use them in your template:
<input type="text" placeholder="Insert name" v-model="name1" />
Access in method by this.name1
Try this
<div id="app">
<h1> Finds </h1>
<div v-for="find in finds">
<input name="name[]" v-model="find.name">
<input name="email[]" v-model="find.email">
</div>
<button #click="addFind">
New Find
</button>
<pre>{{ $data | json }}</pre>
</div>
Vue Component
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ name: '', email: '' });
}
enter code here
}
});

Multer can not get the upload form data in Express 4

I'm using Ajax to upload the form data. The output of multer(req.file, req.body) is always undefined/{};
My server code:
import multer from 'multer';
import post from './router/api_post';
var upload = multer({dest: 'uploads/'});
app.use('/api/post', upload.single('thumb') , post);
and the api_post router file:
import express from 'express';
var router = express.Router();
router
.post('/', (req, res, next) => {
console.log("POST POST");
var post = {};
console.log(req.body);
console.log(req.file);
});
export default router;
the output of req.body is {} and of req.fileisundefined`.
I use react on the browser side and upload data via ajax:
savePost(ev) {
ev.preventDefault();
var editor = this.refs.editorDom.getDOMNode();
var ajaxReq = new AjaxRequest();
var formData = new FormData();
formData.append('post_id', this.state.post_id);
formData.append('title', this.state.title);
formData.append('author', this.state.author);
formData.append('digest', this.state.digest);
formData.append('content', editor.innerHTML);
formData.append('content_source_url', this.state.content_source_url);
formData.append('create_time', new Date());
formData.append('thumb', this.state.thumb);
ajaxReq.send('post', '/api/post', ()=>{
if(ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
var result = JSON.parse(ajaxReq.getResponseText());
if(result.ok == 1) {
console.log("SAVE POST SUCCESS");
}
}
}, '', formData);
}
The savePost() is callback of a button's event listener. I did upload data successfully with formidable. I just replaced the formidable with multer but can not get it.
I didn't set the content-type property. I found it in the header is
, multipart/form-data; boundary=----WebKitFormBoundary76s9Cg74EW1B94D9
The form's HTML is
<form id="edit-panel" data-reactid=".ygieokt1c0.1.0.1.0.1">
<div id="title" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.0">
<input type="text" class="form-control" name="title" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.0.1">
</div>
<div id="author" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.1">
<input type="text" class="form-control" name="author" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.1.1">
</div>
<div id="thumb" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.2">
<button class="btn btn-default" data-reactid=".ygieokt1c0.1.0.1.0.1.2.1">
<input type="file" name="thumb" accept="image/*" data-reactid=".ygieokt1c0.1.0.1.0.1.2.1.0">
<span data-reactid=".ygieokt1c0.1.0.1.0.1.2.1.1">UPLOAD</span>
</button>
</div>
<div class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.3">
<textarea class="form-control" name="digest" rows="5" data-reactid=".ygieokt1c0.1.0.1.0.1.3.1"></textarea>
</div>
<div id="rich-text-editor" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.4">
<div id="editor-div" class="form-control" contenteditable="true" data-reactid=".ygieokt1c0.1.0.1.0.1.4.1"></div>
</div>
<div id="content-source-url" class="form-group" data-reactid=".ygieokt1c0.1.0.1.0.1.5">
<input type="text" class="form-control" name="content_source_url" value="" data-reactid=".ygieokt1c0.1.0.1.0.1.5.1">
</div>
<button class="btn btn-default" data-reactid=".ygieokt1c0.1.0.1.0.1.6">保存并提交</button>
</form>
I can output the thumb, it's a File{} object.
Thanks for help.
Finally I found the problem is the Content-Type.
I used this.request.setRequestHeader("Content-Type", postDataType); to set the Content-Type and set the postDataType to '', then the actual Content-Type in header is , multipart/form-data; boundary=----WebKitFormBoundary76s9Cg74EW1B94D9 as I mentioned at the first.
You can see there is a comma and a space before the multipar/form-data. I have no idea where this comma come from. But anyway, when I remove the comma and space, everything just works fine!