link1233 link1234 link1235 link1236 link1237 link1238 link1239 link1240 link1241 link1242 link1243 link1244 link1245 link1246 link1247 link1248 link1249 link1250 link1251 link1252 link1253 link1254 link1255 link1256 link1257 link1258 link1259 link1260 link1261 link1262 link1263 link1264 link1265 link1266 link1267 link1268 link1269 link1270 link1271 link1272 link1273 link1274 link1275 link1276 link1277 link1278 link1279 link1280 link1281 link1282 link1283 link1284 link1285 link1286 link1287 link1288 link1289 link1290 link1291 link1292 link1293 link1294 link1295 link1296 link1297 link1298 link1299 link1300 link1301 link1302 link1303 link1304 link1305 link1306 link1307 link1308 link1309 link1310 link1311 link1312 link1313 link1314 link1315 link1316 link1317 link1318 link1319 link1320 link1321 link1322 link1323 link1324 link1325 link1326 link1327 link1328 link1329 link1330 link1331 link1332 link1333 link1334 link1335 link1336 link1337 link1338 link1339 link1340 link1341 link1342 link1343 link1344 link1345 link1346 link1347 link1348 link1349 link1350 link1351 link1352 link1353 link1354 link1355 link1356 link1357 link1358 link1359 link1360 link1361 link1362 link1363 link1364 link1365 link1366 link1367 link1368 link1369

[Vue.js] outside root element will be ignored error when the syntax seems perfect in vue component

The following code seems ok at first but if examined in chrome debugger I see some error message “outside root element will be ignored”

The complete code is here:

JS fiddle

the template value of the vue.js component certainly has only one top root containing div element, but strangely the debugger reports that it is not.
The following is the template definition part of the component:

template:
`<div class=”modal fade” v-show:”visible”>
<div class=”modal-dialog” role=”document”>
<div class=”modal-content”>
<div class=”modal-header”>
<slot name=”header”></slot>
<button type=”button” class=”close” data-dismiss=”modal” aria-label=”Close”>
<span aria-hidden=”true”>×</span>
</button>
</div>
<div class=”modal-body”>
<slot></slot>
</div>
<div class=”modal-footer”>
<slot name=”footer”></slot>
<button type=”button” class=”btn btn-primary”>Save changes</button>
<button type=”button” class=”btn btn-secondary” data-dismiss=”modal”>Close</button>
</div>
</div>
</div>
</div>`,

The error message disappear if I enclose the whole template with additional redundant div.

Solution :

You have an error in using v-show

<div class=”modal fade” v-show:”visible”>

It should be:

<div class=”modal fade” v-show=”this.visible”>

Most likely the extra : breaks the vuejs parser and ends up splitting the div declaration in two.

[Vue.js] Vue component Vuex option block feature

While reading Vuex repository docs, I came across the following syntax:

export default {
template: ‘…’,
data () { … },
// NOTICE SYNTAX BELLOW
vuex: {
getters: {
count: function (state) {
return state.count
}
}
}
}

Notice the syntax of vuex option block of the component.

When referencing to either the official Vuex docs or official vue.js 2 API docs, the usage of vuex component option, smiliar to the one above, is not mentioned.

The only thing I understand about this block is (according to Vuex repository docs):

Note the special vuex option block. This is where we specify what state the component will be using from the store.

What is the actual usage of vuex block? can it be used instead of component binding helpers? such as mapGetters and mapState?

Seems like the official docs are lack of docs about this feature.

I’d like to have further information about this feature, thank you.

Solution :

It think it is pointing out the case that one can individually decide on a component basis whether vuex shall be used or not.

The initial example in the vuex docs injects the store on a global level into all vue.js instances, meaning that all components have access to the store.

If you’d like to have more control over which component uses vuex you can go for a explicit declaration of using vuex - for each component individually by using the syntax you are referring to.

[Vue.js] Nuxt js - passing object params in dynamic route

I’m using the following link to dynamic routes

<nuxt-link :key=”$route.fullPath” :to=”{ name: ‘items-id’, params: { parent: { id: item.parent.id, description: item.parent.description } }”>Click me</nuxt-link>

So navigating to /items/ correctly passes the specified params. But if i click another nuxt-link with different params, while being on the /items/ url then nothing happens. I imagine it’s because the url doesn’t really change.

What’s the best way to “reload” the url with new params?

I’ve considered using path which would be different for each nuxt-link

<nuxt-link :key=”$route.fullPath” :to=”{ path: ‘/items/‘ + item, params: { parent: { id: item.parent.id, description: item.parent.description } }”>Click me</nuxt-link>

But this makes the URL ugly as it includes the object ref

Solution :

Just watch() the params (probably the id) and reload data when they change:

watch: {
id() {
// reload the item here
},

},

Solution 2:

Using watch should do it. Just update the variable you want to change according to the value for example if you want to watch for the id variable then set it to a component variable that you will want to be displayed.

watch: {
id (value) {
this.VARIABLE = value
}
}

[Vue.js] How to give dynamic URL in <router-link> in VueJS?

when using v-for directive to get URL name. However, when facing difficulty in passing the value obtained from a instance of v-for as URL name.

<template>
<v-list-tile class=”pl-5” v-for=”choice in choices” :key=”choice.name”>
<v-list-title-content>
<router-link to=”‘/‘ + choice.name”>
<v-list-title-title class=”white–text headline”>
{choice.name}
</v-list-title-title>
</router-link>
</v-list-title-content>
</v-list-tile>
</template>

<script>
export default{
data(){
return{
choices:[
name:’A’,
name:’B’,
name:’C’,
name:’D’
]
}
}
}
</script>

Solution :

You need to bind to. Try something like this

<router-link :to=”‘/‘ + choice.name”>

Solution 2:

You need to bind the choice name like any other variable property: Use v-bind:to or the shorthand form :to.

Here are the docs to v-bind: https://vuejs.org/v2/api/#v-bind

You can also directly bind an object to the to directive, passing along the name of the route, so that you need to concat a path. Like this:

<router-link :to=”{ name: ‘choice1’ }”>Link</router-link>

Solution 3:

Well, In order to make any attributes to dynamic, you need to use v-bind directive.

Short-hand property for v-bind is :

Hence you can use it as below

<router-link v-bind:to=”‘/‘ + choice.name”>

With short-hand

<router-link :to=”‘/‘ + choice.name”>

Official v-bind doc

Hope it helps!

[Vue.js] How to prevent csrf attack if jwt token stored in cookie with httponly in laravel and Vue spa?

Frontend: vue.js spa

Backend: laravel

Frontend and backend are separated, and they are communited with xhr request.

In the beginning I use local storage to store the JWT token, but now I found out that is not very secure.

Thank you for the reply.

Solution :

Add the csrf_token in the html head as a meta tag

<meta id=”token” name=”token” content=”{ csrf_token() }”>

Then in the Vue.js Main File add this token to the vue.js Instance.

Vue.http.headers.common[‘X-CSRF-TOKEN’] = document.querySelector(‘#token’).getAttribute(‘content’);

[Vue.js] Can't upload image only on mobile device Laravel + Vue

I read about this on some posts on the stack, but I still do not see the same case as mine. I can not upload the image on phone device. I do not see why I do not have a console to see error. I’ll show you the code, so someone who is experienced can see the error.

Laravel code to upload image:

public function uploadImage($car, $images)
{
$fileName = Carbon::now()->timestamp . $images->getClientOriginalName();
$path = $images->move(public_path(‘public/images’), $fileName);
if (!$path) {
return response()->json([‘message’ => ‘An error has accured’], 500);
}
$carImage = new CarImages ([
‘path’ => ‘public/images/‘ . $fileName
]);

$car->images()->save($carImage);
return $carImage;
}

Laravel code for store form with image:

public function store(CarRequest $request)
{
$file = null;
if ($request->has(‘picture’)) {
$file = $request->file(‘picture’);
}
$user = auth()->user();
if ($user) {
$car = Car::create([
‘car_type’ => $request->input(‘car_type’),
‘mark’ => $request->input(‘mark’),
‘model’ => $request->input(‘model’),
‘user_id’ => $user->id
]);
}
if (!$car) {
return response()->json([‘message’ => ‘Oooops, something went wrong’], 500);
}
if ($file) {
$carImage = $this->uploadImage($car, $file);
}
Mail::to($user->email)->send(new NotifyNewCarUpload($user, $car));
return response()->json([
‘message’ => ‘the car has been successfully added’,
‘car’ => $car,
‘user’ => $user
], 201);
}

In CarRequest for upload for car i have:

‘car_type’ => ‘required’,
‘mark’ => ‘required’,
‘model’ => ‘required’,
‘picture’ => ‘required|image’

In Vue.js insert car I have:

<form enctype=”multipart/form-data” accept-charset=”utf-8”
@submit.prevent=”submit”>


<div class=”col-3 insert-vehicle-right”>
<div :class=”{ ‘error’: errors.has(‘file’) }” v-if=”!imgSrc” class=”image-upload-holder”></div>
<img :class=”{ ‘error’: errors.has(‘file’) }” v-if=”imgSrc” class=”uploaded-image” :src=”imgSrc” alt=”uploaded image”/>
<div class=”upload-btn-wrapper”>
<button class=”btn action-btn”>Upload Photo</button>
<input name=”file”
v-validate=”‘required’”
type=”file”
@change=”onFileChange”/>
</div>
</div>
</div>
<div class=”row”>
<div class=”col-12”>
<button type=”submit” class=”btn action-btn save-btn”>Save</button>
</div>
</form>

Vue.js javascript code for upload and preview image code:

onFileChange(event) {
this.picture = event.target.files[0];
const file = event.target.files[0];
this.imgSrc = URL.createObjectURL(this.picture);
},

And there is formData code for post that code:



formdata.append(‘picture’, this.picture);

It’s not working on mobile phones. Does anyone recognize the reason?
All my pictures are stored in the laravela folder public/public/images and work good on web browser (destop and laptop device). Also there is table for storing path images.. Only for phone device not work. Help?

Solution :

Okey problem was be in php.ini configuraction and max_size_upload file. I only set more than 2mb images file and work perfecty.
@thanks Rasa

[Vue.js] same uuid two times + Vuex + uuidv4()for those who need this

there is inside my vuex store a function to create a post. And the function returns a json Object with a unique uuid from uuidv4(). But if I run the function two times (or more) I get the same uuid and that’s a problem.
(Only if I reload the page I get a new uuid).

// store.js
import uuidv4 from ‘uuid/v4’;
var uuid = uuidv4();
const state = {
postDetails: {

uuid: uuid,

}
}

const actions = {
post ({state}) {
var postArray = []
postArray.push(state.postDetails)
// some axios stuff…
}
}

So everything works fine. The main problem is the uuid which doesn’t change after the function is called.

I use vuex-persistedstate also

Solution :

for those who need this

Solved my problem. there is added a function which creates a uuid without page reload.

function uuidv44() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}

With help from this site Create GUID / UUID in JavaScript?

[Vue.js] Axios request receiving a CORS error only when inside a callback/async function

I’m using VueJS for an app when building. The server there is is written in Golang and has been set to accept CORS. In the app, in one of my components, searchBar, there is set it to fetch some data before it is created.

var searchBar = {
prop: […],
data: function() {
return { … };
},
beforeCreate: function() {
var searchBar = this;

axios.request({
url: ‘/graphql’,
method: ‘post’,
data: {
‘query’: ‘{courses{id, name}’
}
})
.then(function(response) {
searchBar.courses = response.data.data.courses;
});
},
methods: { … },
template: `…`
};

Axios works perfectly here. It gets the data I need. searchBar has a button which causes it to emit an event which is then picked up by another component, searchResults. Upon receiving the event, searchResults will fetch some data.

var searchResults = {
data: function() {
return { … }
},
mounted: function() {
var sr = this;

this.$bus.$on(‘poll-server’, function(payload) {
var requestData = {
url: ‘/graphql’,
method: ‘post’,
data: { … },

};

axios.request(requestData)
.then(function(response) {
console.log(response);
}
);
});
},
template: `…`
};

Note that my Axios request call is now inside a callback function. When this call is performed, I receive a CORS error:

Access to XMLHttpRequest at ‘http://127.0.0.1:9000/graphql' from origin ‘http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

My server is located at http://127.0.0.1:9000, with the client in http://127.0.0.1:8080. Here is the content of the OPTIONS request of the second request call.

For comparison, here is the request header of the first request call (that works!).

there is already set my Golang server to support CORS via go-chi/cors. This is how set it up.

router := chi.NewRouter()

// Enable CORS.
cors := cors.New(cors.Options{
AllowedOrigins: []string{“*“},
AllowedMethods: []string{“POST”, “OPTIONS”},
AllowedHeaders: []string{“Accept”, “Authorization”, “Content-Type”, “X-CSRF-Token”},
ExposedHeaders: []string{“Link”},
AllowCredentials: true,
MaxAge: 300,
})

router.Use(
render.SetContentType(render.ContentTypeJSON),
middleware.Logger,
middleware.DefaultCompress,
middleware.StripSlashes,
middleware.Recoverer,
cors.Handler,
)

router.Post(“/graphql”, gqlServer.GraphQL())

return router, db

What is causing the error when having and how can it be solved?

Solution :

This CORS error is expected. The CORS plugin you are using does request filtering for you. If you look at the list of allowed headers, you can see it’s missing the header called snb-user-gps-location that you are trying to send in the axios call.

Either add that header to the allowed list, or don’t send it from the front end.

Solution 2:

I still suspect the go-chi CORS setup. I would suggest looking at setting up CORS by hand. It’s not that difficult. This page will get a basic setup: https://flaviocopes.com/golang-enable-cors/

If that works with the nested API setup, we can then work backwards to determine the go-chi config issue.

Update:

I would also investigate the other middleware steps - commenting out all non-essential ones.

Middleware handlers normally inspect the r *http.Request or write headers to the w http.ResponseWriter and then the final handler will write to the response body. But throughout the middleware chain the following header/body write flow should look like one of these two flows:

Success:

w.Header().Set(…) // headers
w.Write(…) // body

Note the above flow will issue an implicit http status code write, to keep headers appearing first and body second:

w.Header().Set(…) // headers
w.WriteHeader(http.StatusOK) // implicit success http status code
w.Write(…) // body

Failure:

In the event of reporting a runtime error, the flow should be:

w.Header().Set(…) // headers
w.WriteHeader(http.StatusInternalServerError) // some unrecoverable error
w.Write(…) // optional body

The reason I bring this up, I’ve seen 3 types of bugs which mess up this flow:

bad middleware handlers write headers after the body causing client confusion
calling http.Error thinking that stops the API dead - instead of returning immediately after the http.Error and ensuring no subsequent middleware handlers are called
write the same header twice. Rewriting headers in a subsequent handler will cause the client to see the last version (thus clobbering any previous versions)

So to fully trace things, I would log.Println all header/body writes for the API to ensure the above flow is correct and no intended values are being overwritten.

Solution 3:

What you are missing is Access-Control-Allow-Origin. This is a response header telling the browser that cors is allowed for this domain. Check if there is a problem with the cors configuration. A configuration problem perhaps? Maybe you need to allow it for 120.0.0.1:8080.

[Vue.js] CORS policy No 'Access-Control-Allow-Origin' / 500 (Internal Server Error) Problemcontroller codeclient code

Basically, I’m trying to get a username by id from Sequelize. The problem is that when either stuck with a CORS problem or 500 Internal Server error depending on the response(status)

cors and 500

controller code

async getUserFromUserId (req, res) {
try {
// const user = await User.findByPk(req.body.id)
const id = req.body.id
const user = await User.findByPk(id)
res.send(user.username)
} catch (err) {

// or res.status(some random number).send() for CORS problem to appear

res.status(500).send({
error: ‘an error has occured trying to fetch the users id’
})
}
},

client code

this.notifiedUser = (await UserService.getUserFromUserId({id: UserId})).data

I get a Status: 200 OK from postman though.
Postman Solution

Edit:
there is seen how the other Solution for the cors thingy, but the solutions does not specify as to why I get “undefined” results after resolving the cors problem.

Solution :

So, CORS is actually really obnoxious in this regard, but there’s a fairly straightforward way to fix this. It’s a super useful security feature, though it is frustrating at best sometimes.

the browser does what is called a Preflight Request, which is of the http verb OPTIONS. the browser calls whatever route you want, but instead of what you asked it to do, it calls using OPTIONS first. the server should accept all routes that the client can ask for with the OPTIONS method, and the server should respond with the following headers to be an externally available, cross-origin API.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, …

(note, you should not put the … in, but you can put any HTTP verb in this list)

If you require the own headers (for auth purposes), you want to add this header for Client -> Server.

Access-Control-Allow-Headers: YourHeader, YourHeader2, YourHeader3

You want to add this one for Server -> Client

Access-Control-Expose-Headers: YourHeader,YourHeader3

Note that the OPTIONS call is an entirely separate call that you should handle as well as the GET method.

You’ve now told the browser what it is allowed to ask for, and what it can expect to get back from the API. If you don’t respond to the OPTIONS request, the browser terminates the request, resulting in a CORS error.

I’m going to take a gander at a guess and assume you’re likely using Express, which this answer describes how to set the headers on.

What do the headers mean, in English?

Access-Control-Allow-Origin
From where are clients allowed to access this resource (endpoint)? This can match partial domains with wildcards, or just a * to allow anywhere.

Access-Control-Allow-Methods
What HTTP methods are permissible on this route?

Access-Control-Expose-Headers
When I get a response from the server, what should I (the browser) expose to the client-side?

Access-Control-Allow-Headers
What am I as the client side allowed to send as headers?

Solution 2:

If the origin is from localhost, Chrome usually blocks any CORS request originating from this origin.

You can install this extension:

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

Or you can disable the security when running chrome (add the flag):

--disable-web-security

[Vue.js] Intercepting network errors on apollo-module using Nuxt

I’m using nuxt with apollo-module and I need to intercept possible network errors (401/403’s to be more specific) so I can show some error modal and log out my user. In the documentation I see that inside the nuxt.config.js you can do like:

apollo: {
tokenName: ‘Authorization’,
authenticationType: ‘Bearer’,
errorHandler(error) { do something }
}

But inside that config file, I can’t access the app features that I need (like a errors modal or my router, for instance). Is there any way to archive it?

Solution :

You can use apollo-error-link

apollo: {
clientConfigs: {
default: ‘~/apollox/client-configs/default.js’
}
},

And here config

import { onError } from ‘apollo-link-error’

export default function(ctx) {
const errorLink = onError(({ graphQLErrors, networkError }) => {

})
return {
link: errorLink,

// required
httpEndpoint: ctx.app.$env.GRAPHQL_URL,

httpLinkOptions: {
credentials: ‘same-origin’
},
}
}