How to connect the frontend library to laravel? - laravel

how to properly connect third-party plug-ins when developing on laravel?
I need the fullpage.js library
downloaded it via npm
in the resources/js/bootstrap.js file I added require ('fullpage.js');
In the resources/js/app.js file I added
$ (document) .ready (function () {
    $ ('. js-fullpage'). fullpage ({});
});
I launch the project and I see in the console
app.js: 4655 jQuery.Deferred exception: $ (...). fullpage is not a function TypeError: $ (...). fullpage is not a function
    at HTMLDocument. <anonymous> (http: // localhost: 3000 / js / app.js: 770: 21)
    at mightThrow (http: // localhost: 3000 / js / app.js: 4371: 29)
    at process (http: // localhost: 3000 / js / app.js: 4439: 12) undefined
app.js: 770 Uncaught TypeError: $ (...). fullpage is not a function
as if it does not see the connection it's a library ..
and generally my call code from resources/js/app.js is why you are ABOVE than resources/js/bootstrap.js, although they are connected in a different order
my bootstrap file
try {
window.$ = window.jQuery = require('jquery');
} catch (e) {
}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found:https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
require('fullpage.js');

Can you try to include it like
require('fullpage')
or you can try to pass full path

Add it to your webpack.mix.js and run npm run dev or npm run prod depending on your environment:
mix.js([
'resources/assets/js/app.js',
'path/to/fullpage.js',
], 'public/js/app.js')

Related

Deployed Laravel sanctum application not working anymore

I use sanctum for my vue Axios operations. I deploy to my shared hosting and I get this error in the chrome console:
GET http://foo.xyz/city 401 (Unauthorized)
bootstrap.js :
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios.defaults.withCredentials = true;
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Axios Get :
getCity() {
axios.get('/api/city')
.then((response) => {
this.cities= response.data;
})
.catch(function (error) {
console.log(error);
});
},
Everything is working in my localhost when I deployed this project into my shared hosting nothing worked, so how I can run this in my shared hosting?
I added the following code to the .env
SANCTUM_STATEFUL_DOMAINS="foo.xyz"
and problem solved.
PS:
foo.xyz is not the actual domain, I gave a different domain for security reasons.

Get Vuex store reference in cypress with vue-cli

I'm following along this tutorial to get the vuex store in cypress while running e2e tests.
As I use vue-cli (#vue/cli 4.3.1), with the #vue/cli-plugin-e2e-cypress.
As of this setup, I don't have an app.js, rather a main.js.
But if I put the needed code in the main.js, it does not work:
/**
* Start APP
*/
const app = new Vue({
router,
render: h => h(App),
}).$mount('#app');
if (window.Cypress) {
console.log('Running in Cypress');
// only available during E2E tests
window.app = app;
} else {
console.log('NOT Running in Cypress');
}
If I run it from cypress, I doesn't log anything from main.js to the console.
In cypress, when I try to get the store
cy.window().its('app.$store')
I get the error:
Timed out retrying: cy.its() errored because the property: app does not exist on your subject.
How can I get it running with vue-cli?

Uncaught ReferenceError: axios is not defined in Vue.js

I am creating a SPA application with reference to the following tutorial.
http://voerro.com/en/tutorials/r/building-spas-with-laravel-5-and-vuejs-2/1
Until yesterday The top page displayed without error.
But, Today I started virtual machine again and accessed it,
The following javascript error occurs.
Uncaught ReferenceError: axios is not defined
at new Auth (app.js:53626)
at Module../resources/js/app.js (app.js:53554)
at __webpack_require__ (app.js:20)
at Object.0 (app.js:54214)
at __webpack_require__ (app.js:20)
at app.js:84
at app.js:87
I tried to review Git's log, but there was not a history that changed.
Do you know how to resolve this??
class Auth {
constructor () {
this.token = window.localStorage.getItem('token');
let userData = window.localStorage.getItem('user');
this.user = userData ? JSON.parse(userData) : null;
if (this.token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.token; // <-this is the error point
}
}
....
export default Auth;
app.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Auth from './auth.js'
import Api from './api.js';
window.api = new Api();
window.auth = new Auth();
Vue.use(VueRouter);
bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] =
'XMLHttpRequest';
Either use window.axios or import axios from 'axios' or vue.prototype.$axios = axios. It's a scoping issue. Don't rely on globals.
I realized the problem was caused due to commenting out or removing
require('./bootstrap'); /****in app.js ***/
That is if you are working with Vue in Laravel.
Note: This is not twitter Bootstrap for UI

Laravel VueJS axios interceptor accessing the vue application

I've got what's basically the default Vue JS scaffolding that comes with Laravel.
// app.js
require('./bootstrap');
window.Vue = require('vue');
const app = new Vue({
el: '#app',
methods: {
refreshToken: function() {
console.log('refreshing the token');
}
}
});
// bootstrap.js
window._ = require('lodash');
window.Popper = require('popper.js').default;
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
This should be familiar to anyone who has used Vue JS with Laravel before.
Now i've tried to add an axios interceptor to handle errors, i've done this below the X-Requested-With header in bootstrap.js
window.axios.interceptors.response.use(
response => response,
error => {
// Show the user a 500 error
if (status >= 500) {
console.log({500:error});
}
// Handle Session Timeouts
if (status === 401) {
console.log({401:error});
app.refreshToken();
}
// Handle Forbidden
if (status === 403) {
console.log({403:error});
}
return Promise.reject(error)
}
);
The console.log() instances work fine to verify that it is working.
However app.refreshToken() does not work (and does not give an error either?).
I'm not that surprised since I haven't imported it or anything.
But i've tried this at the top of bootstrap.js: import app from './app.js';
And npm run watch now throws a warning:
"export 'default' (imported as 'app') was not found in './app.js'
I modified app.js to change const app to be export const app but this didn't make any difference.
I'm pretty sure I am just missing some basic understanding of importing and exporting within es6 but unfortunately I can't find anything on Google that will explain it.
Most of my Googling of how to setup this axios interceptor to handle errors has come up with examples using vuex. I really don't want to bring in vuex just to resolve this as I don't want to touch it until i'm sure it's necessary for my particular app and it definitely seems overkill just to be able to follow a tutorial.
How can I call my app.refreshToken() method or access my vue instance within the axios interceptor?
After
require('./bootstrap');
window.Vue = require('vue');
const app = new Vue({
el: '#app',
methods: {
refreshToken: function() {
console.log('refreshing the token');
}
}
});
Add what the error says it's missing:
"export 'default' (imported as 'app') was not found in './app.js'
Just add this:
export default app;
That might solve the compilation problem, as for the call to the function, i have not tested it yet... came with a very similar problem 15 minutes ago..

react-native unable to resolve module 'events'

I have created an empty project with the following command:
react-native init demoProject
after installing
npm install -g react-native-cli
then I have installed mongoDB with the following command:
npm install mongodb --save
In the package.json file I have the following:
"dependencies": {
"events": "^1.1.1",
"mongodb": "^2.2.31",
"react": "16.0.0-alpha.12",
"react-native": "0.47.1"
},
In the index.ios.js file I am trying to import the mongodb as the following:
var MongoClient = require('mongodb').MongoClient;
After building the project in Xcode I have this error:
bundling failed: "Unable to resolve module `events` from `/Users/rzilahi/work/demo01/node_modules/mongodb/lib/apm.js`: Module does not exist in the module map
what am i doing wrong?
Why are you importing MongoClient to index.ios.js ? It shouldn't be imported in the index or any other file of your app. Database queries should be done in a webservice. So in your app, you can use fetch to retrieve data from a webservice and render that with a FlatList or component of choice. You can create a NodeJS project on port 1337 (example port) and run the Node Server. In that Node Project you need to import MongoClient and query the DB for data and use res.send or res.json to send the data back as a response. So if you're able to access your webservice at http://localhost:1337/getdata , you're all set.
You may need to use your actual IP address of the computer in fetch, like:
fetchData(){
fetch('http://192.168.0.4:1337/getdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson})
})
.catch((error) => {
alert(error);
});
}
And your node server would look something like:
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
mongoose.Promise = global.Promise;
var app = express();
//create the Posts Schema or import it.
app.get("/getdata", function(req, res){
Posts.find({}, function(e,doc){
if(doc==null){
res.send("NO POSTS");
}
else{
res.json(doc);
}
});
});
app.set('port', (process.env.PORT || 1337));
app.listen(app.get('port'), function(){
console.log("Server started on port: " + app.get('port'));
});

Resources