link2466 link2467 link2468 link2469 link2470 link2471 link2472 link2473 link2474 link2475 link2476 link2477 link2478 link2479 link2480 link2481 link2482 link2483 link2484 link2485 link2486 link2487 link2488 link2489 link2490 link2491 link2492 link2493 link2494 link2495 link2496 link2497 link2498 link2499 link2500 link2501 link2502 link2503 link2504 link2505 link2506 link2507 link2508 link2509 link2510 link2511 link2512 link2513 link2514 link2515 link2516 link2517 link2518 link2519 link2520 link2521 link2522 link2523 link2524 link2525 link2526 link2527 link2528 link2529 link2530 link2531 link2532 link2533 link2534 link2535 link2536 link2537 link2538 link2539 link2540 link2541 link2542 link2543 link2544 link2545 link2546 link2547 link2548 link2549 link2550 link2551 link2552 link2553 link2554 link2555 link2556 link2557 link2558 link2559 link2560 link2561 link2562 link2563 link2564 link2565 link2566 link2567 link2568 link2569 link2570 link2571 link2572 link2573 link2574 link2575 link2576 link2577 link2578 link2579 link2580 link2581 link2582 link2583 link2584 link2585 link2586 link2587 link2588 link2589 link2590 link2591 link2592 link2593 link2594 link2595 link2596 link2597 link2598 link2599 link2600 link2601 link2602

[Vue.js] flask-CORS extension doesn't work. What am I doing wrong?

This question already has an answer here:

CORS Error: requests are only supported for protocol schemes: http etc

2 answers

I’m developing a website using Flask, Vuejs and Webpack. The server and the client are separated into two folders and in development I’m running the server using flask run and the client (Vuejs) using yarn serve.

So the frontend is coming together nicely, and I now want to start doing some calls to the server. Since the client is served on port 8080, and the server on port 5000 I’m getting CORS errors. To avoid these I’m trying to use the flask-cors extension.

I’ve copied exactly what they do in the example:

from flask import Flask
from app.config import Config
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.config.from_object(Config)
CORS(app)

And instead of the last line I also tried the resource specific example:

cors = CORS(app, resources={r”/api/*“: {“origins”: “*“})

Unfortunately I’m still getting CORS errors in the frontend.

As far as I understand the server side should send along headers which allow cors, but I’m not actually seeing a request in the browser network tab, I just get an error in the console.

Also, it says only the protocol schemes http […] https are allowed. I’m doing an ordinary http request, so I’m not sure why that wouldn’t work.

And from here I’m kinda lost. Does anybody know how I can debug this?

Solution :

Ok, nevermind. I now realise I didn’t add http:// to my request..

Thanks for listening anyway.. :-)

[Vue.js] electron ipcRenderer from Vue.js Single File Component Subscribe to RSS

I’m trying to use Electron’s ipcRenderer inside my vue.js sigle file component to populate some data. It easy enough to call out with a ipcRenderer.send(…) but on the reply to update each instance of my component with the response message. I think the comment in ipcRenderer.on(…) explains my issue the best. Is there a good way to do this. I’m completely new to JS.

<template>
<v-container fluid>
<v-btn @click=”do_action()”>{title}</v-btn>
<v-textarea v-model=”response_message”>
</v-textarea>
</v-container>
</template>

<script>
const { ipcRenderer } = require(‘electron’)

export default {
props: [‘title’],
data: function(){
return {
response_message: “Original Message”
}
},
methods: {
do_action: function() {
ipcRenderer.send(‘cmnd_foo’)
}
},
}

ipcRenderer.on(‘cmnd_foo-reply’, (event, a_new_message) => {
// obviously this.response_message isn’t in scope…
// how can I get this intent to work
this.response_message = a_new_message
})
</script>

Solution :

I seem to have found a way to do it. Maybe there is still a better way?

<template>
<v-container fluid>
<v-btn @click=”do_action()”>{title}</v-btn>
<v-textarea v-model=”response_message”>
</v-textarea>
</v-container>
</template>

<script>
const { ipcRenderer } = require(‘electron’)

var catcher = 0;
function setMessage(msg) {
this.response_message = msg
}

export default {
props: [‘title’],
data: function(){
return {
response_message: “Original Message”
}
},
methods: {
do_action: function() {
catcher = setMessage.bind(this)
ipcRenderer.send(‘cmnd_foo’)
}
},
}

ipcRenderer.on(‘cmnd_foo-reply’, (event, a_new_message) => {
catcher(a_new_message);
})
</script>

Solution 2:

Just add remote at the end:

const { ipcRenderer } = require(‘electron’).remote

[Vue.js] Not sure why my Vue app build.js file appears to be my index.html file after build in Firebase Subscribe to RSS

After I deploy my vue.js app to Firebase, it appears as if my build.js file is the same as my index.html file. When I go the site, I get nothing. Looking the the console, I get an error Uncaught SyntaxError: Unexpected token < at line 1 of build.js.
If I then reload it with the Network tab open, I see build.js listed as a resource, but when I click on it, it shows the same contents as index.html. (The build.js file is in fact js after I build it on my end).

This is my first time using Firebase, so I’m not sure if I’m doing something wrong in the firebase.json (which I just copied from a tutorial):

{
“hosting”: {
“public”: “./dist”,
“ignore”: [
“firebase.json”,
“**/.*“,
“**/node_modules/**“
],
“rewrites”: [{
“source”: “**“,
“destination”: “/index.html”
}]
}
}

I’m not using any other firebase tools.

Thanks for any insight.

Solution :

you firebase.json should look like this:

hosting”: {
“public”: “dist”,
“ignore”: [
“firebase.json”,
“**/.*“,
“**/node_modules/**“
],
“rewrites”: [
{
“source”: “**“,
“destination”: “/index.html”
}
]
},

Run firebase deploy –only hosting and it should be good. Source here

Make sure the output for that command looks something like this:

\=== Deploying to ‘your-project-name’…

i deploying hosting
i hosting[zero-to-prod-test]: beginning deploy…
i hosting[zero-to-prod-test]: found 16 files in public/build <—- THIS TELLS YOU IF THE FILES ARE BEING COPIED
hosting[zero-to-prod-test]: file upload complete
i hosting[zero-to-prod-test]: finalizing version…
hosting[zero-to-prod-test]: version finalized
i hosting[zero-to-prod-test]: releasing new version…
hosting[zero-to-prod-test]: release complete

That way to can debbug is something is wrong on the data transfer.

On the case the index.html is pointing to dist/build.js intead of /build.js that is causing the problem, so it doesnt look like a firebase problem but a webpack problem. Check the assets generation process.

[Vue.js] How can I ensure my not yet fetched data doesn't break my site Subscribe to RSS

when currently building a like button on my card component in vue. when fetching data from firebase using middleware on a page to dispatch the vuex action that will go and get my user info which has their liked_posts stored in an array.

The issue comes up that when I load a page requiring some of the data
i.e. liked_posts and my state is empty it throws a error of
“undefined”.

How can I make sure that even if the user hasn’t signed in or hasn’t ever visited that my user data wont cause an error

there is tried to change my action in the Vuex store to be asynchronous and use await so that I made sure the data was there, but it didn’t help.
What is happening is the below code in computed properties is trying to access an object that doesn’t exist in the array yet.

likedOrNot() {
const likeInfo = this.$store.state.userInfoSub[0].liked_posts
return likeInfo.includes(this.$store.state.loadedCards[0].id)
}

This data isn’t there yet because the user isn’t signed in, exist ect. once they do and middleware is dispatching an action to fetch the user data the userInfoSub will be filled with info.

my base state looks like this when the user hasn’t signed in or middleware hasnt fired to look for the user that gets put in cookies.

So I need away to ensure my lack of userInfoSub doesn’t break my computer property

loadedCards:Array[1]
0:Object
token:null
user:null
userInfoSub:Array[0]
username:null

Solution :

Here’s an opinionated answer: use get from lodash.

npm i lodash

Then you can write something like this:

import get from ‘lodash/get’;

export default {
computed: {
isLiked() {
const cardId = get(this.$store, ‘state.loadedCards[0].id’);
const postIds = get(this.$store, ‘state.userInfoSub[0].liked_posts’, []);
return postIds.includes(cardId);
},
},
};

[Vue.js] How to instantly redirect the user to a new page via router when the user logs in succesfully(password, username are correct) Subscribe to RSS

Via vue.js I’ve made a login form with a username and password, and set conditions for them. When the user submits the correct username and password to redirect them to a new page vie the vue.js Router. So for example if the user is currently located in “localhost8080/“, after a successful login to immediately send them to “localhost8080/#/profile”

validate() {
var email = document.getElementById(“email”).value;
var atSign = email.indexOf(“@”);

var error = document.getElementById(“error”);
var mistakes = “”;
var hasErrors = false;

if (this.newP != this.password){
mistakes += “Entered password is incorrect. “;
hasErrors = true;
}

if (atSign === -1) {
mistakes += “The email is missing an ‘@’ sign.”;
hasErrors = true;
}
// console.log(this.newP.length)
if (hasErrors === true) {
error.innerHTML = mistakes;
return false;
} else {
alert(“Login confirmed”);
return true;
//I realize it’s supposed to be here, but I do not know
//how to write it.
}
}

Solution :

If You using vue-router, better to use programmatic navigation.

Link: https://router.vuejs.org/guide/essentials/navigation.html

if(loginConfirmed) {
this.$router.push({ path: ‘dashboard’ });
}

[Vue.js] Will I lose performance by specifying a value that I might not use in a dynamic component in Vue.js? Subscribe to RSS

In my app, there is 10 components, all of which require a property called andamento; but only a subset require a property called custas.

If I set the custas property for all components in andamentosOrdenado (below), will I lose performance versus setting the property for only a subset?

Here is my code:

<v-timeline-item class=”mb-3” small v-for=”andamento in andamentosOrdenado” :key=”andamento.nome”>
<component v-bind:is=”andamento.form” :andamento=”andamento” :custas=”notificacao.custas”></component>
</v-timeline-item>

Solution :

If the value of custas is static/constant:

No, because you can’t “lose” performance for not using a constant value/variable, this is because the property has already been defined and it’s value has already been evaluated (a process that doesn’t need to happen again).

If the value of custas isn’t static/constant:

Then yes, because you’re making the machine waste resources on evaluating a non-static value that you’re most likely not going to use. Not to mention that this value might change, meaning it’s value would be re-evaluated (for no reason).

An alternative solution to this problem would be to use an if statement to define the custas property conditionally, for example:

// pseudo code:
if (i_need_custas) {
my_object.custas = fn_that_returns_value_that_might_change();
}

Then, where you need to use custas:

// pseudo code:
if (my_object.hasOwnProperty(“custas”)) {
// do stuff with custas
}

Good luck.

[Vue.js] MongoDB _id returns undefined on frontend (VueJS) Subscribe to RSS

I created a simple fullstack webapp using NodeJS & Express + MongoDB to build the backend API and Vue.JS for the frontend.

All the Write Read and Delete API worked perfectly (I tested it using Postman). Everything works perfectly as well on the frontend, except when I tried to iterate (v-for) on an array of objects to get the _id, it doesn’t work.

The array called posts has the attributes of ‘text’ and ‘createdAt’. The v-for works perfectly and output the 2 attributes as expected. However, I tried to output _id (default id from MongoDB) but it returned “undefined”.

This causes a problem because if I can’t get _id, it wouldn’t be possible for me to delete a specific post using the existing backend delete API.

From my understanding, in the backend side, the _id needs to be converted into ObjectId first before it can be used for db querying. But on the frontend (vue) when not sure on how can turn _id into ObjectId. Am I getting into the right direction here?

<div class=”post” v-for=”(post,i) in posts “ :key=”post._id” :index=”i” :item=”post” @dblclick=”deletePost(post._id)”>
{post.createdAt.getDate()}/{post.createdAt.getMonth() + 1}/{post.createdAt.getFullYear()}
<p class=”text”>{post.text}</p>
</div>

methods: {
async deletePost(id){
console.log(id) //this returns undefined
await PostService.deletePost(id);
this.posts = await PostService.getPosts();
}
},

//del post in PostService.js
static deletePost(id){
return axios.delete(url+id)
}

//backend delete api

router.delete(‘/:id’,async (req,res)=>{
const posts = await loadPostCollection()
console.log(ObjectID(req.params.id))
await posts.deleteOne({_id: ObjectID(req.params.id)});
res.status(200).send()
})

expected output: _id of each ‘post’, e.g:5cfa8c29f74c65ae485a6d93
actual output: undefined

no error message(s).

Solution :

You need to add the property reference post, like this:

<div class=”post” v-for=”(post,i) in posts “ :key=”post._id” :post=”post” @dblclick=”deletePost(post._id)”>
{post.createdAt.getDate()}/{post.createdAt.getMonth() + 1}/{post.createdAt.getFullYear()}
<p class=”text”>{post.text}</p>
</div>

Solution 2:

You don’t have to convert _id to Mongo ObjectID on the FrontEND.

the code looks normal, send all post object to function like that and debug it.

@dblclick=”deletePost(post)”

Probably the backend return _id as an object.

[Vue.js] How to get around vuetify's v-select internal state Subscribe to RSS

I’m trying to prevent a value from being ‘selected’ when using vuetify’s v-select component.

Given:

<v-checkbox
v-model=”allowChanges”
\></v-checkbox>
<v-select
v-model=”twoWayComputed”
:items=”items”
\></v-select>

new Vue({
el: ‘#app’,
data: () => ({
selected: “Foo”,
allowChanges: false,
items: [‘Foo’, ‘Bar’, ‘Fizz’, ‘Buzz’]
}),
computed: {
twoWayComputed: {
get(){
return this.selected
},
set(val){
if (this.allowChanges){
console.log(“updating”)
this.selected = val
}
}
}
}
})

Codepen: https://codepen.io/anon/pen/mYNVKN?editors=1011

When another value is selected, the components selected value is not being updated. However v-select still shows the new selected value.

I even tried all kinds of “tricks” like

set(val){
if (this.allowChanges){
console.log(“updating”)
this.selected = val
} else {
this.selected = this.selected
}

but no luck.

I believe v-select is maintaining its own internal selected value.

Solution :

I made it using slot-scope look:

<v-select
v-model=”twoWayComputed”
:items=”items”
label=”scoped”
\>
<template slot=”selection” slot-scope=”data”>
{ selected }
</template>
<template slot=”item” slot-scope=”data”>
{ data.item }
</template>
</v-select>

data: () => ({
selected: “Foo”,
allowChanges: false,
items: [‘Foo’, ‘Bar’, ‘Fizz’, ‘Buzz’]
}),
computed: {
twoWayComputed: {
get(){
return this.selected
},
set(val) {
if (this.allowChanges) {
console.log(“updating”)
this.selected = val
}
}
}
}

check-out-my-codepen

[Vue.js] How to use S3 bucket URL as the base URL for images on components Subscribe to RSS

when using S3 bucket to save user’s profile images and the image they are uploading. On my components to use the image base url to the S3 bucket

I declared a variable on main.js

window.s3bucket = ‘https://myassets.s3.us-east-2.amazonaws.com';

and then in component when trying to use it as :

<img alt=”” :src=”s3bucket+’/user/‘+ userimage”>

but when getting error as s3bucket is not defined or its not a function.

Solution :

Correct. Don’t hang variables off the window if you’re not in a UMD environment.

Instead, you could just assign this to vue.js directly:

Vue.prototype.$s3bucket = ‘https://myassets.s3.us-east-2.amazonaws.com';

Notice I’ve used $ above so you don’t have potential collisions.

Then just use:

:src=`${$s3bucket}/user/${userimage}…`

(You don’t have to use template strings, I just prefer the syntax)

[Vue.js] vue-tables-2 pagination doesn't limit per page amount Subscribe to RSS

I’m using vue-tables-2 as datatable in my vue.js app.
vue-tables-2: ^1.4.70
vue: ^2.6.10
everything is fine except showing items per page which is limited by perPage on options object.
Here there is 5 records and I had set per page option to 2. but its not working and still showing 5 records per page. Also when I click on page two noting changes!
Here is my code:

tickets.vue:

<template>
<v-server-table url=”/panel/tickets/data” :columns=”columns” :options=”options”></v-server-table>
</template>
<script>
export default ({
name: ‘ticketTable’,
data() {
return {
columns: [‘subject’, ‘status’, ‘department’, ‘date’],
options: {
responseAdapter(data) {
return {
data,
count: data.length
}
},
headings: {
subject: ‘’,
status: ‘’,
department: ‘’,
date: ‘ ‘
},
perPage: 2,
pagination: {
edge: false,
dropdown: false,
chunk: 2
},
filterable: true,
sortable: ‘subject’,
}
}
}
});
</script>

app.js:

import ticketTable from ‘./components/tickets’;
import {ServerTable} from ‘vue-tables-2’;

Vue.use(ServerTable, {
texts: {
count: “ {from} {to} {count} “,
first: ‘’,
last: ‘’,
filter: “ : “,
filterPlaceholder: “”,
limit: “:”,
page: “:”,
noResults: “ “,
filterBy: “ {column}”,
loading: ‘ …’,
defaultOption: ‘ {column}’,
columns: ‘ ‘
}
});

html:

<section class=”mt-4 mb-4”>
<div class=”section-title”>
<h4 class=”mb-0”> </h4>
</div>
<div class=”section-content”>
<ticket-table></ticket-table>
</div>
</section>

Here is my result:

Any help is appreciated.

Solution :

prop values is validating. Allowed only 10,25,50 or 100.

If you want to change this go to plugin folder and find the code line where is it. Or use this.$refs.table.setLimit(2)
On load set the value …

mounted:function(){
this.$refs.table.setLimit(2)
},

<v-client-table ref=”table” :columns=”columns” :data=”data” :options=”options”>
<a slot=”uri” slot-scope=”props” target=”_blank” :href=”props.row.uri” class=”glyphicon glyphicon-eye-open”></a>

<div slot=”child_row” slot-scope=”props”>
The link to {props.row.name} is <a :href=”props.row.uri”>{props.row.uri}</a>
</div>

</v-client-table>

Example of usage