Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked) - api

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer

For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

How to pass header in Axios post request

Here is my code:
const data = {
listing: listing,
};
await axios.post('https://app.jghfjgf.com/m/api/helper/helper', qs.stringify(data) ,{
headers:{
'Cookie':cookie,
'content-type': 'application/x-www-form-urlencoded'
}}
).then(response =>{
console.log(response);
alert(response.data);
}).catch(error => {
console.log(error);
alert(error);
});
I am trying to make HTTP request using Axios library and I tried most of the suggestions available on the web. I don't know what mistake I am doing. I am new to React Native application so don't have enough practice with Axios.
Note: The issue is value "cookie" in header is not passing along with the API so I am facing error.

React Native - Axios POST with urlencoded params

I successfully triggered POST request via Postman to retrieve mobileSession key. But when I tried the same from React Native app (via Axios), I get error that some params are missing. Can someone tell me what is wrong in Axios according to Postman request which is working?
Postman:
And Axios code:
export function getMobileSession() {
let requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let body = {
username: 'myusername',
password: 'mypw',
api_key: 'apikey',
api_sig: 'signature',
method: 'auth.getMobileSession',
format: 'json'
};
return axios.post('Lastfm_API_URL', JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
}
Try this,
return axios.post(`https://ws/audioscrobbler.com/2.0/`, JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
For more refer here to know about back tick.

Fetch with devise_token_auth in react-native

I'm new with react-native. I'm trying to satisfy the devise_token_auth requirement of send in every request the authetication headers. To do so, I'm trying something like this:
export const scheduleFetch = (auth) => {
return (dispatch) => {
fetch(URL, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'access-token': auth['acessToken'],
'token-type': auth['tokenType'],
'client': auth['client'],
'uid': auth['uid']
}
})
.then((response) => {
console.log(response)
response.json()
})
.catch((error) => console.log(error))
}
}
My back-end is receiving the request, all headers are fill. However, I still receiving the message "_bodyText":"{\"errors\":[\"You need to sign in or sign up before continuing.\"]}".
How can I make that work? Am I jumping any step?

Aurelia: fetch-client response doesn't have my data

I've been banging my head against fetch-client for too long and I need some help.
I'm getting some data from Skyscanner. The request hits their API and Chrome's dev tools list it in the network tab as a complete fetch request with code 200 and the correct response body.
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
#inject(HttpClient)
export class Flights {
constructor(http){
http.configure(config => {
config
.withBaseUrl('http://partners.api.skyscanner.net/apiservices/')
.withDefaults({
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-type' : 'application/json'
}
});
});
this.data = "";
this.http = http;
}
activate() {
this.http.fetch('browsequotes/v1.0/GB/GBP/en-GB/UK/anywhere/anytime/anytime?apiKey=MYAPIKEYGOESHERE')
.then(response => {
console.log(response);
console.log(response.response);
console.log(response.content);
console.log(response.data);
})
.catch(ex => {
console.log(ex);
});
}
}
But when the response object is printed it has NOTHING in it:
Response {}
body: null
bodyUsed: false
headers: Headers
__proto__: Headers
ok: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response
All of the remaining console.log's produce undefined
Am I using fetch-client incorrectly? What am I missing?
Notice you're receiving an opaque response (type: "opaque"). Opaque responses does not allow you to read them. This is due to the no-cors mode you set before. You should use the cors mode and SkyScanner should provide the proper headers for your API key which is something I think they don't do.
I fixed my issue which can fall under same heading so leaving an answer here as I couldn't find anything on the net. May be I'm just stupid but i was doing this before...
.then(response => {response.json()})
.then(data => console.log(data))
Banged my head against this for a day and turned out the fix is:
.then(response => response.json())
.then(data => console.log(data))
Or
.then(response => { return response.json()})
.then(data => console.log(data))
Simple really and nothing to do with Aurelia or Fetch but understanding of Javascript syntax.