Vue Dynamic URL From state. In axios call - api

I want to parse the axios url call from a variable state in vuex. As simple as this:-
state: {
getOrganizationURL: "opensource",
}
actions: {
getOrganizationDashboard({commit, state}) {
axios
.get(`"https://xxx/api/report/"${state.getOrganizationURL}`, {
headers: {
Authorization: `Bearer ${state.currentAuthToken}`,
},
})
.then(response => {
commit("setOrganizationsDashboardData",response.data)
});
},
}
when checking the network on the browser. The API call is going to a weird url instead.
e.g
Request URL: http://localhost:8080/%22https://xxxx/api/report/%22opensource
which leads to page not found...
I think it a minor mistake. Any tips please?

Related

How to get data correctly using the Spotify API with React

I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data:
`
import axios from 'axios';
const BASE_URL = 'https://api.spotify.com/v1';
export const fetchFromAPI = async (url: string, token: string) => {
const { data } = await axios.get((`${BASE_URL}/${url}`), {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return data;
}
`
Next, I use the fetchFromAPI function:
`
const { token } = useContext(Context);
const [albums, setAlbums] = useState<string[]>([]);
useEffect(() => {
fetchFromAPI('browse/new-releases', token)
.then((data) => console.log(data));
}, [token])
`
I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is
Ok, I managed to find and solve this error myself.
The error was that I didn't have a user token yet, but useEffect was already starting to receive data.
useEffect(() => {
if (token) {
fetchNewReleases();
fetchFeaturedPlaylists();
fetchCategories();
fetchRecommendations();
} else {
console.log('error');
}}, [token])
For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.
To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API

Vuex store cannot be used inside axios handler

I have method being successfully called by a button in my Vue component:
methods: {
goTestMe() {
console.log(this.$store.state.lang+' 1')
let url = 'some api url'
let headers = { headers: { 'Content-Type': 'application/json' } }
this.$axios
.get(url, headers)
.then(function(response) {
console.log('here')
console.log(this.$store.state.lang+' 2')
})
The problem is that the output of this is:
en-us 1
here
When it should be:
en-us 1
here
en-us 2
Clearly, the reference to this.$store.state is failing in the then() handler of the axios call.
Why is this? How can I send data received by my axios request to the Vuex store?
when you add the callback in the normal function you can't access the global object so you need to change it to an arrow function
methods: {
goTestMe() {
console.log(this.$store.state.lang+' 1')
let url = 'some api url'
let headers = { headers: { 'Content-Type': 'application/json' } }
this.$axios
.get(url, headers)
.then((response) => { // change it to arrow function
console.log('here')
console.log(this.$store.state.lang+' 2')
})
}

Put API KEY in axios

I just started learn React but I have problem when I trying to make a request to the CoinMarketCap API with axios and tried several ways to set my API key. I have also also tried on Postman but message appears API key missing.
export const apiBaseURL = 'https://pro.coinmarketcap.com';
Tried like this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`,
{ headers =
{ 'X-CMC_PRO_API_KEY': 'apicode', }
})
this
dispatch({ type: FETCHING_COIN_DATA })
let config = { 'X-CMC_PRO_API_KEY': 'apicode' };
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`, { headers: config })
and this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?X-CMC_PRO_API_KEY=apicode`)
Thank you
The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
Adding the key to the default headers was the only way I could get this to work.
Use CMC_PRO_API_KEY as a query parameter, instead of X-CMC_PRO_API_KEY:
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?CMC_PRO_API_KEY=apicode`)
I realize this has been solved; for the sake of alternatives here is how I did it. I created a instance of axios in /includes/axios:
import axios from "axios";
const instance = axios.create({
baseURL: "https://example.com/api",
headers: {
"Content-Type": "application/json",
"x-api-key": "****API_KEY_HERE****",
},
});
export default instance;
Now axios can be imported anywhere in the project with the give configuration. Ideally you want to add your secret to the ENV variable for security reasons.

How to handler server redirect from axios

I have a vue web app that uses axios to communicate with an API. The authentication is handled by the server, and not by my app. That is, the server ensures that the user cannot see the app before they have authenticated.
Of course, after some time the user's authentication token expires and my app only notices this when it fires off a get/post request to the API. When this happens the axios request returns a redirect to a login page that, when printed to the console, looks something like this:
config: Object { url: "https://...url for my request...",
method: "get", baseURL: "...base url for api", … }
data: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<HTML>\n<HEAD>\n<TITLE>Need Authentication</TITLE>\n<link rel=\"stylesheet\" href=\"/Steely.css\" type=\"text/css\">\n</HEAD>\n<BODY>....</BODY>\n</HTML>\n"
headers: Object {
connection: "Keep-Alive",
"content-encoding": "gzip", "content-length": "1686", …
}
request: XMLHttpRequest {
readyState: 4, timeout: 0, withCredentials: false, …
}
status: 200
statusText: "OK"
<prototype>: Object { … }
app~d0ae3f07.235327a9.js:1:97292
What is the best way to redirect the user to this login page and then resume my original request? At the moment I am not even succeeding in recognising this. My axios code tries, and fails, to recognise when this happens and then redirect to user a vue component that has a login page. The relevant part of code looks like this:
export default new class MyAPI {
constructor() {
this.axios = axios.create({
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
},
baseURL: `https://.../api`,
});
}
// send a get request to the API
GET(command) {
return new Promise((resolve, reject) => {
this.axios.get(command)
.then((response) => {
if (response && response.status === 200) {
if ( response.data && typeof response.data == 'string' && response.data.includes('Require authentication') ) {
store.dispatch('authenticate', this.baseURL+'/'+command).then( (resp) => resolve(resp.data) )
} else {
resolve(response.data);
}
} else {
reject(response.data);
}
})
.catch((err) => { reject('Internal error'+err); });
});
}
}
This results in the dreaded
Internal errorTypeError: e(...) is undefined
error, although this error is almost certainly triggered further down the code since I not recognising the login authentication request.
Is anyone able to recommend how best to recognise and process the login request?

Problem with PUT request in axios with vue.js

I'm building a smart home application. I have a problem with sending PUT request to my rest api (I building it with flask), but when I try send request it gives me HTTP 400 error (( Uncaught (in promise) Error: Request failed with status code 400 )) . Can you help me?
import axios from 'axios';
export default {
data: function() {
return {
value: 0,
lampName: 'Kitchen',
};
},
mounted () {
axios
.get("http://127.0.0.1:5000/lamp/" + this.$route.params.id)
.then(response => (this.value = response.data))
},
methods: {
updateValue () {
axios
.put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
}
}
try to add the method field to the form and send it in post way like this
formData.append('_method', 'PUT')
then try to send the data regularly
I think it work like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
import axios from 'axios';
export default {
data: function() {
return {
value: 0,
lampName: 'Kitchen',
};
},
mounted () {
axios
.get("http://127.0.0.1:5000/lamp/" + this.$route.params.id)
.then(response => (this.value = response.data))
},
methods: {
updateValue () {
let formData = new FormData();
formData.append("value", this.value);
formData.append("lampName", this.lampName);
formData.append('_method', 'PUT');
axios
.post('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
formData
})
}
}
}
</script>
So this is the failing request:
axios
.put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
I don't know what your server is expecting but you're setting a content-type of application/x-www-form-urlencoded while sending JSON data. It seems likely this mismatch is the cause of your problems. You should be able to see this if you inspect the request in the Network section of your browser's developer tools.
If you need to use application/x-www-form-urlencoded then I suggest reading the axios documentation as you can't just pass in a data object like that:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
In short, you need to build up the body string manually, though there are utilities to make that less onerous.
If you actually want JSON data then just remove the content-type header. Axios should set a suitable content-type for you.
Pass your method as post method and define put in form data formData.append('_method', 'PUT') .
updateValue () {
axios
.post('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value, _method: 'PUT'},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}