I've deployed a VueJS project to a domain like www.example.com/demos/app,
But when I send a request to api from axios it is pointing to www.example.com/login instead of www.example.com/demos/app/login
Here is my request code using axios
export const login = ({ dispatch }, { payload, context }) => {
return axios.post('/login', payload).then((response) => {
// do something
}).catch((error) => {
// handle erros
})
}
One way you could go about this is to add a meta tag to the head of your page (like you may do with the csrf) and then reference it in your bootstrap.js file:
head
<meta name="api-base-url" content="{{ url('demos/app') }}" />
bootstrap.js (underneath window.axios = require('axios');)
window.axios.defaults.baseURL = document.head.querySelector('meta[name="api-base-url"]').content;
Hope this helps!
In config.js:
const CONFIG = {
API_URL_ROOT: 'http://localhost:8000/api/v1/',
}
export default CONFIG;
You can set axios default like this:
import config from '../config.js';
axios.create({
baseURL: config.API_BASE_URL
});
Or you can just set path by importing API_BASE_URL from config and then point it each time you make a get/post/put/delete call using axios
Laravel ships with axios and its imported in bootstrap.js, so simply go to bootstrap.js and add this:
window.axios.defaults.baseURL = 'http://example.test';
You can add this after window.axios.defaults.headers.common line
-Additional information:
axios.create will make an instance that has its own global url and configurations. use this if you have multiple urls or configuration and you want to use it in different components.
Create vue.config.js in Project root directory( if not exist ) -
In vue.config.js -
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/demos/app/'
: '/'
}
Then, Add the line in resources/js/bootstrap.js -
const {publicPath} = require("../../vue.config");
window.axios.defaults.baseURL = publicPath
.env
MIX_APP_URL="${APP_URL}"
resources/js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.baseURL = process.env.MIX_APP_URL;
Update your APP_URL in .env file and add the above code on respective files.
Related
following https://nuxtjs.org/api/configuration-env
I have been trying to set up my apiUrl in nuxt.config.js once for the whole project, like:
export default {
env: {
apiUrl: process.env.MY_REMOTE_CMS_API_URL || 'http://localhost:1337'
}
}
adding this in nuxt.config.js, I'd expect (and would like) to have apiUrl accessible everywhere in the project.
In particular, it is needed for the 3 following cases:
with axios, to generate static pages from dynamic urls (in nuxt.config.js)
generate: {
routes: function () {
return axios.get(apiUrl + '/posts')
.then((res) => {
return res.data.filter(page => {
return page.publish === true;
}).map(page => {
return {
route: '/news/' + page.slug
}
})
})
}
},
with apollo, to get data via graphql (in nuxt.config.js)
apollo: {
clientConfigs: {
default: {
httpEndpoint: apiUrl + '/graphql'
}
}
},
in every layout, page and components, as the base url of media:
<img :src="apiUrl + item.image.url" />
As you might see, only thing I need is to 'print' the actual base url of the cms.
I have also tried to access it with process.env.apiUrl, with no success.
The only way I was able to make it has been to create an extra plugin/apiUrl.js file, which injects the api url, and seems wrong to me as I am now setting the apiUrl twice in my project.
I asked this question in the past, but in a way less clear way. I was suggested to use dotenv, but from the docs it looks like adding an additional layer of complication that might not be necessary for a simpler setup.
Thanks.
I think dotenv module really is what you need.
This is my setup:
Project root has a .env file that contains
BASE_URL=https://www.myapi.com
require('dotenv').config() at top of nuxt.config.js
#nuxtjs/dotenv installed and added to buildModules of nuxt.config.js
env: { BASE_URL: process.env.BASE_URL} added to nuxt.config.js
axios: { baseURL: process.env.BASE_URL } added to nuxt.config.js (optional)
You should have access to your .env throughout the project. (process.env.BASE_URL)
I haven't used apollo, but you should be able to set the apollo endpoint with process.env.BASE_URL + '/graphql'
As of Nuxt 2.13, #nuxtjs/dotenv is not required anymore. Read here
The concept that I was missing is that you set up the same named variable in your server / pipeline, so that you have your (always local / never pushed) .env file and a same name variable remotely, not added to your repo (where the value can be the same or different)
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>
I'm setting configs in my main.js file before calling Vue :
Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'
It works if I access this.$api_url in any Vue file.
But in store.js (Vuex), it's another Vue Instance that is rendered, so I can't access this.$api_url.
What about setting the configs in a file and Vue.use(configs.js) ?
What should I do inside the configs file in order to get its variables in main.js/store.js ?
Thank you.
Make a standalone config.js file and export your config object from that file. And import config where ever you need config.
You can also assign the same config to Vue's prototype if you want that to be provided in all Vue components.
Update:
So here is how you can do this:
In your config.js
let config;
if (process.env.NODE_ENV === "production") {
config = {
$api_url: "https://api.xxx.com",
timeoutDuration: 30000,
someOtherProps: 'xyz'
};
} else {
config = {
$api_url: "https://yyy.test:8443",
timeoutDuration: 1000,
someOtherProps: 'abc'
};
}
export { config }
In your main.js
import { config } from 'config';
Vue.prototype.appConfig = config
use this.appConfig.$api_url whatever way you want to use in .vue files
In your store.js
import { config } from 'config';
use config.$api_url whatever way you want to use
I'm trying to implement Shopify JS SDK in Nuxt
So this is what I did, a plugin
// plugins/shopify.js
import Vue from 'vue'
import 'isomorphic-fetch'
import Shopify from 'shopify-buy'
export default ({ app }, inject) => {
app.shopify = Shopify.buildClient({
domain: 'aaa.myshopify.com',
storefrontAccessToken: 'aaa'
});
}
nuxt config
//nuxt.config.js
plugins : [{ src : '~/plugins/shopify', ssr: false}]
vendor : ['shopify-buy']
index
asyncData ({ app }) {
return app.shopify.product.fetchAll().then((products) => {
// Do something with the products
console.log(products);
return { products : products }
});
}
The result is
TypeError Cannot read property 'product' of undefined
But it works if I removed the asyncData, refresh my page, and add the code back without refreshing.
I believe this has something to do with the lifecycle.
Can anyone please tell me if I'm doing it the right way, or there's other proper way to define such const which can be use across pages, components etc
And if this is the right way, what I did wrong?
Thanks in advance.
My reference are Nuxt guides as well as examples.
I tried google around but can't locate what I need, or maybe I just didn't get the right keywords.
FROM DOCUMENTATION
Nuxt.js lets you create environment variables that will be shared for
the client and server-side.
To do this, you can use the env property:
nuxt.config.js:
module.exports = {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
}
Then to access it from anywhere, just use it like so:
process.env.baseEnv
For example, in an axios plugin:
import axios from 'axios'
export default axios.create({
baseURL: process.env.baseUrl
})
According to the docs, I should put routeAfterAuthentication in my config/environment.js file.
My environment.js contains the following:
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '',
locationType: 'auto',
routeAfterAuthentication: 'dashboard',
...
However, it's still not getting redirected to the dashboard route and showing that the index route is not defined.
Am I missing something here?
You will need to include ember-simple-auth key like this
var ENV = {
};
...
ENV['ember-simple-auth'] = {
authenticationRoute: 'sign-in',
routeAfterAuthentication: 'YOUR ROUTE GOES HERE'
}
...
You can also define them by environment inside if (environment === 'development'), but for all environments you can put them after var ENV declaration. It is also important to import application route mixin so that redirect works (app / routes / application.js)
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {});