Unable to use axios in js function - vue.js

We are building an application using VueJS, are new to its concepts. Facing an error when we try to make a call using axios from a js function.
The error is "export 'default' (imported as axios) was not found in ./axios.js"
Please let us know what we might be doing wrong. Appreciate your help.
import Vue from 'vue';
import axios from './axios.js';
export const MY_CONST = 'Vue.js';
export let memberList = new Vue({
el: '#members',
data: {
members: []
},
mounted: function () {
this.getAllMembers();
},
methods: {
getAllMembers: function () {
var me = this;
axios.get("https://xxxxx.com/services/api.php")
.then(function (response) {
me.members = response.data.members;
});
}
}
});

Assuming you've installed axios as a dependency or devDependency in your package.json and installed it via npm or yarn then I would suspect your issue is that you're looking for axios in a file called axios.js in the same directory as the calling component. You should instead look for the package axios like this:
import axios from 'axios';
If you're indeed trying to export axios from a custom file with configuration or something then you need to see what you're exporting from the file and make sure it is indeed axios. Though from the sound of your error that doesn't seem to be what your'e trying to do.

Related

vuejs with electron, can't use fs

I'm using Vue with it's Electron plugin and I want to use fs to read directories, but it gives me this error. What could be the problem?
TypeError: Object(...) is not a function
import Vue from 'vue';
import Component from 'vue-class-component';
import { readdir } from 'fs';
#Component
export default class Directory {
mounted() {
readdir('C:/', (err, files) => {
if (err) console.log(err);
console.log(files)
})
}
}
I only worked with Angular+Electron combo, but with that I used electron's main process to do file manipulation stuff.
Further read: https://www.electronjs.org/docs/api/ipc-main
In the main process, you can access "fs" easily like you would in node.
I don't know if this is the case with Vue, but maybe this helps.

import js file inside .vue component loaded using httpVueLoader

i want to not use webpak form my vue devlopement,
so there is 2 alternative
writting components as .js file or
writing them as .vue file and use httpVueLaoder to load component as if they are .js file
with httpvueLoader think go grate untile the time i want to use an API inside my component
ther i can not get the API
i have a Home.vue componet inside ther is a FormLot.vue component in witchi try to import API.js
<script>
let FormLot = window.httpVueLoader('./frontEnd/page/lot/FormLot.vue')
module.exports = {
name:"Home",
components: {FormLot:FormLot},
...
};
</script>
in FormLot.vue
// _END_ is the absolut path to the site , soi can change it later
let API = import(_END_+'/api/api.js') // dont work return promise
import API from './frontEnd/api/api.js' // dont work componnet dont show at all :(
let FormLotE1 = window.httpVueLoader(_END_+'/page/lot/FormLotE1.vue')
module.exports ={
...
};
</script>
API.JS
module.exports ={
...
};
API.JS
export default {
...
};
with API.js i tryed export default and module.export bothe dont work
nota
when using webpack API.js got been normaly imported and work fine
when using import API from path httpVueLaoder dont work
so i tried to do
const API= import(path)
problem witch that ,API is promise ,wich can notbe used :(
using await dontsolve the problem even when using
const API = (async ()=> await import(path))()
my solution still to call import using await but not in the top of the script
i call it in the mounted() function
async mounted(){
API = (await import(_END_+'/api/api.js')).default
},
note that you must use .default because import return a module :)
enter code here

properly use ENV Variables in vue-cli

So I'm brand freaking new to Vue-Cli and I'm following a tutorial on using a Vue frontend with a Rails backend. Im configuring Axios to handle my requests.
My problem:
Im trying to set an ENV_VAR on my API_URL constant, at this point when I try to console.log the API_URL I get the following error:
Uncaught ReferenceError: process is not defined
at <anonymous>:1:13
I have the following to config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
ENV_API_URL: '"http://localhost:3000/api/fuzeisp/v1"'
})
and I am trying to call that ENV in src/backend/axios/index.js
import axios from 'axios'
const API_URL = process.env.ENV_API_URL
const securedAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application.json'
}
})
I have tried to read the docs, but for some reason i cant make heads or tails of this! any assistance here would be greatly appreciated! Please, If you need more information i would be happy to provide it for you!
Thanks in advance.
The vue cli is using the dotenv to parse .env files with their content, adding their content to the process.env object. However, these variables will only be available at build-time (since process.env is a global property of the node environemnt).
Code at client-side will not have access to the process object at all. However, vue cli helps out! It reads process.env variables at build time and replaces them with their corresponding values - so you can use them in your client side code. NOTE: It only replaces those variables prepended with VUE_APP_; e.g. VUE_APP_BASE_URL=www.myapp.com.
Read more about it here
so I was able to log the output of VUE_APP_ENV_API_URL by adding the following in my App.vue file:
<script>
export default {
name: 'App',
mounted () {
console.log(process.env.VUE_APP_ENV_API_URL)
}
}
</script>

Problem when importing js-cookies in Main.js

I'm trying import js-cookies in my main.js
Main.js
import * as Cookies from "js-cookie";
Vue.use(Cookies)
Using in component
this.$Cookies.set('name', data.user, { secure: true });
Error
TypeError: Cannot read property 'set' of undefined
what is the problem?
I have tried a thousand ways and it still does not work.
Vue.use(name) is used to install a vue plugin. The package will need an install method that receives a vue instance.
#1
You can use the cookies packages without a plugin importing the module in the component
<script>
import Cookies from 'js-cookie';
export default {
methods: {
addCookie() {
console.log('adding the cookie');
Cookies.set('chocolate', 'chookies');
console.log(Cookies.get());
}
}
}
</script>
#2 you can add a VUE plugin and set a Cookies prototype function to the Cookies module.
(Prototype vue functions will be available for components, it's standard to prefix them with $).
src/CookiesPlugin.js
import Cookies from 'js-cookie';
const CookiesPlugin = {
install(Vue, options) {
Vue.prototype.$Cookies = Cookies;
}
};
export default CookiesPlugin;
src/main.js
import CookiesPlugin from './CookiesPlugin';
Vue.use(CookiesPlugin);
In the component
this.$Cookies.set('chocolate', 'chookies');
console.log(this.$Cookies.get());
You are using a NOT Vue (Vanilla JS library) library and you are trying to use it as a Vue resource.
Try using this one instead

Populate router with external json

I would like to add routes from an external json file, which can change at runtime, to my Nuxt application. A similar topic can be found here.
I've overridden the default Nuxt router with my own implementation. If I import the routes async using axios + router.addRoutes(), I seem to loose the server side rendering. It seems like createRouter will have async support, but it's not in an official release of Nuxt yet.
How do I import a js/json file synchronously to my router.js below, so that I can populate the routes? I want to be able to configure the routes at runtime, so I don't want it to be a part of the bundle.
modules/router.js:
const path = require('path')
module.exports = function () {
this.nuxt.options.build.createRoutes = () => {}
this.addTemplate({
fileName: 'router.js',
src: path.resolve(`${this.options.srcDir}`, 'router.js')
})
}
nuxt.config.js:
modules: ['~/modules/router']
router.js:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export function createRouter () {
const router = new Router({
mode: 'history',
routes: [/* ... */]
})
return router
}
You could try with sync-request.
It is a NPM package aimed to perform synchronous web requests. It is available here.
Please note that, as stated in the documentation of the package itself, it is not suitable for production environment, probably because of application hanging in case of missing data.
So await would be an answer but I guess you already tried that? So, something like this.
const routeFile = await fetch('pathToTheJsonFile');
const routes = await routeFile.json();
In case you can't make the method async, as a workaround maybe use jQuery. I don't like this but if there's no other option, for now, use async: false in jQuery get.
jQuery.ajax({
url: 'pathToYourJsonRoutes',
success: function (result) {
},
async: false
});