How do I set the baseUrl so if I switch from server to server on the frontend (Vue.js), it changes dynamically to baseUrl?
I show my code axios-auth.js code:
import axios from 'axios'
const instance = axios.create({
baseURL: 'http://mvp.test/api/public/api/'
// baseURL: 'http://127.0.0.1:8000/api/' for testing localhost
});
and my .env file which have standard code for laravel.
Taken from the official mix documentation, you can use an environment variable by creating a key in your .env prefixed with MIX_:
MIX_BASE_URL=http://mvp.test/api/public/api/
And run php artisan config:clear to be sure the new config is set.
Then, in javascript you can access the variable inside the process.env object:
process.env.MIX_BASE_URL
So you can simply use it like this:
const instance = axios.create({
baseURL: process.env.MIX_BASE_URL
});
Related
I need to copy the behaviour of, for example, the "create" function of Axios:
// fileOne.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://some-domain.com/api'
});
Then to use that baseURL in another file, with another function like this:
// fileTwo.js
import axios from 'axios';
axios.get('/user/12345'); // https://some-domain.com/api/user/12345
Getting this as result:
https://some-domain.com/api/user/12345
How does Axios to bind the baseURL data in his library.
I'm looking that library but i don't understand how they do that.
Please see the official documentation Config Defaults section.
You can specify config defaults that will be applied to every request.
Global axios defaults
axios.defaults.baseURL = 'https://some-domain.com/api';
// use it later
axios.get('/user/12345')
Custom instance defaults
const instance = axios.create({
baseURL: 'https://some-domain.com/api'
});
// use it later
instance.get('/user/12345')
Source code explanation of axios v1.2.1
The Axios class has a defaults
property, axios will merge config when dispatch a request. The axios package will call createInstance to create an axios instance of the Axios class with built-in default config.
There is a buildFullPath function to build the full request URL use baseURL and requestedURL(Absolute or relative URL to combine, in your case, it's /user/12345)
So firstly i create custom axios instance with baseurl and export it like this:
import axios from 'axios';
const instance = axios.create({
baseURL: process.env.BACKEND_URL,
});
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
instance.defaults.headers.post['Content-Type'] = 'application/json';
export default instance;
The problem is in my saga or in any component in general (ONLY client side) when importing this custom axios instance. I use next-redux-wrapper, and when i prefetch data (using getStaticProps) for my component everything works fine and the axios.defaults.baseURL property works just fine.
However the problem is on client-side, whenever i import the same axios instance in any component or in saga but i call it from lets say componentDidMount, the same axios.default.baseURL is undefined, so if i want to make get request i have to type in the full backend + queries URL. What could the problem be? EXAMPLE:
export function* fetchTPsSaga() {
try {
console.log(axios.defaults.baseURL);
const url = `/training-programs`;
const res = yield axios.get(url);
const tPs = res.data.data;
yield put(fetchTrainingProgramsSuccess(tPs));
} catch (err) {
yield put(fetchTrainingProgramsFail(err));
}
}
// The first time it renders (on server side), it's the valid baseURL property, however if i call the same saga from client-side (when component is rendered) it's UNDEFINED, so i have to type the full url
process.env only work on server-side. You can use publicRuntimeConfig to access environment variables both on client and server-side.
next.config.js
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
backendUrl: process.env.BACKEND_URL,
},
}
axios instance file
import axios from 'axios';
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
const instance = axios.create({
baseURL: publicRuntimeConfig.backendUrl,
});
By the way, if you are using Next.js versions 9.4 and up, the Environment Variables provide another way.
Loading Environment Variables Rules
In order to expose a variable to the browser you have to prefix the variable with
NEXT_PUBLIC_
. For example:
NEXT_PUBLIC_BACKEND_URL='http://localhost:3000'
Then you can access this env variable in Axios as its client-side rendering
import axios from 'axios';
const instance = axios.create({
baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
});
*Note: You have to use process.env.NEXT_PUBLIC_BACKEND_URL instead of process.env.BACKEND_URL
I have Vue app that has to use some PHP scripts. If I place them on server everything works fine and I am able to make Axios request like:
this.$http
.post("http://my-domain.com/scripts/news.php", {
action: "getAll"
})
Still, I would like to have those scripts in my local development environment and use them like this:
this.$http
.post("/scripts/news.php", {
action: "getAll"
})
with scripts placed in public/scripts. When tried with PHP dev server or Apache I could only use them when requesting http://localhost/scripts/news.php and proxing PHP server with vue.config.js, but it is not useful since I would need to change that when switching to production.
How to configrue it properly?
try setting up the base url of axios.
import axios from 'axios'
window.axios.defaults.headers.common = {'X-Requested-With': 'XMLHttpRequest'}
window.axios.defaults.baseURL = (process.env.NODE_ENV !== 'production') ? 'http://my-domain.com/' : ''
Recently I am studying ReactJS.
I want to set a global configuration variable such as SERVER_IP_ADDR.
So, when I ask the server for an API (get / post) as Ajax,
I would like to use this global configuration variable in ReactJS.
I usually create a global variable in JavaScript,
Just import it and use it anywhere.
/js/config.js
var SERVER_IP_ADDR
/js/main.js
<script src="/js.config.js"></script>
and like this
<script>
function request() {
url = SERVER_IP_ADDR;
}
</script>
Can not I set up this structure in ReactJS?
You could export a configuration object and import it wherever you need it.
js.config.js
const config = {
SERVER_IP_ADDR: '...',
OTHER_CONFIG_KEY: '...'
}
export default config;
and in the file you need it
import configuration from "./js.config"
function request(){
fetch( configuration.SERVER_IP_ADDR );
}
If you use create-react-app, You should use .env variables for such thing.
Add .env file in your root path, file content would be like this:
REACT_APP_SERVER_IP_ADDR=http://myapi.com
REACT_APP_CUSTOM_VARIABLE=foobar
then in your source code, you can use it like this:
${process.env.REACT_APP_SERVER_IP_ADDR}/v1/user
More info regarding .env: .env
yes you can , you can use the config.js file and use it multiple places.
your config.js file looks like
module.exports={
url : 'api.xxx.com'
}
and you can import it like
import config from './config';
config.url
I have code like this in my git respository, but it is not a good idea beacuse my API keys are exposed in strings and everyone can see it.
So my question is how can I handle this problem? Should I save this API keys to *.txt file and import this strings?. And add this txt file to .gitignore file?
Can you suggest what would be the proper way of tackling this problem?
import axios from 'axios';
export const FETCH_LOCATION = 'FETCH_LOCATION';
export const FETCH_WEATHER = 'FETCH_WEATHER';
export const HISTORY_SELECTED = 'HISTORY_SELECTED';
export const SHOW_INFO = 'SHOW_INFO';
const API_KEY_GOOGLE = 'string';
const API_KEY_WUNDERGROUND = 'string';
export function fetchLocation(city) {
const urlGoogle = `https://maps.googleapis.com/maps/api/geocode/json?address=${city}&key=${API_KEY_GOOGLE}`;
const request = axios.get(urlGoogle);
A common practice is to use .env files, and ignore .env in .gitignore. You will load these files into process.env. You can use a package called dotenv.
For example, if I need a google API, I create a file call .env, then store it like
GOOGLEAPIKEY=asdfewvger343sdfasdf
If you are loading it with webpack, then add it as a plugin
import DotEnvPlugin from 'webpack-dotenv-plugin';
plugins: [
new DotenvPlugin({
sample: './.env.default',
path: './.env.dev',
}),
...
]
Or you can just use dotenv
require('dotenv').config()
This will load .env file from your root without config.
Read more on this
https://github.com/motdotla/dotenv
In your app, you will use googleapi, like process.env.GOOGLEAPIKEY
const data = await axios
.post(`localhost:3000/api/helloworld/${process.env.GOOGLEAPIKEY}`)
.send(data.fetchData);