Axios formData with image is sending empty array - vue.js

I have a put method to my profile route in the backend, I need a token authentication so in order to be authorized I have to pass the token through a header, I get an error because for some reason it's sending an empty formData when I log the request in my backend.
I tested the backend with postman and everything works as intended so it's not a backend issue, it's totally something wrong in the request I'm doing from the frontend, but I don't know how to handle this, any clue?
profile_update() {
let params = {
email: this.profile.email,
password: this.profile.password,
coin: this.profile.coin,
phone_country: this.profile.phone_country,
phone_area: this.profile.area_code,
phone_number: this.profile.number,
first_name: this.profile.first_name,
last_name: this.profile.last_name,
date_of_birth: this.profile.date_of_birth,
gender: this.profile.gender,
city_id: this.profile.city,
wants_to_change_password: this.profile.wants_to_change_password,
state_id: this.profile.state,
city_id: this.profile.city
}
let headers = {
'Authorization': 'Bearer' + this.token
}
let formData = new FormData();
formData.append('profile-picture', this.profile.profile_picture)
formData.append('data', params)
formData.append('headers', headers)
formData.append('_method', 'PUT')
axios.put(`http://127.0.0.1:8000/api/profile`, formData, headers).then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
}

Try this way
axios.put(`http://127.0.0.1:8000/api/profile`, {'profile-picture':this.profile.profile_picture}, {
headers: {
Authorization: 'Bearer ' + this.token,
'content-type': 'multipart/form-data'
}
}).then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
Hope this may solve your problem. For more info read docs

Related

Upload Image to server with React-Native

My name is Leo. I'm trying to upload avatar to server. I find that everyone always use Formdata to upload. But in my case i need 2 key in form-data (avt, email), so how can i deal with that. Thank you very much!
Here are my testing in Postman
For your use-case, you can build the formData like:
let data = new FormData();
data.append('avt', {
name: '<file_name>',
type: '<file_type>', // e.g. 'image/png'
uri: '<file_uri>',
});
data.append('email', 'test#email.com');
If you are using fetch to make the API request, then your request can be like:
fetch('<api_url>', {
method: '<api request method>',
body: data,
headers: {
'Content-Type': 'multipart/form-data',
// ...other headers
}
})
.then((response) => response.json())
.then((response) => {
console.log('upload file response: ', response)
})
.catch(() => {
console.log('upload file error: ', error);
});
If you are using axios to make the API request, then your request can be like:
axios({
url: '<api_url>',
method: '<api request method>',
data: data,
})
.then((response) => {
console.log('upload file response: ', response)
})
.catch(() => {
console.log('upload file error: ', 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 is not working

I am waiting for successful JSON from server:
{"...."}
Actual Behavior
I get
SyntaxError: Unexpected token b in JSON at position 0
b is the first letter of word "badlogin". It responds server when sent wrong combination of userName and password. But when I use Postman with the same key values combination on the same address I get correct rosponse from the server.
Steps to Reproduce
fetch('http://....', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userName: "react",
password: "123",
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.message);
if(responseJson.success === true) {
alert('successufuly loged');
}
else{
console.log(responseJson.message);
alert(responseJson.message);
}
})
}
}
You are trying to parse a string. This is the error. Instead of always parse the json, just add a clausule to check if the request was made with success
}).then((response) => {
if(!response.ok) {
// handle your error here and return to avoid to parse the string
return
}
return response.json()
})
.then()
Look like the response you got is not json
Try to check what is the response you are getting first:
.then((response) => response.text())
.then((responseJson) => {
console.log(responseJson);
}
I solved this issue by using FormData to prepare data for sending:
......
login = () => {
var formData = new FormData();
formData.append('username', 'react');
formData.append('password', '123');
fetch('http://......', {
method: 'POST',
body: formData
........

AXIOS : Send Authorization header returns Error 401, Authorization Header missing

I came around this solution but this is not working for me.
Following is my code:
axios.post('http://myurl/api/login', {
email: 'john#doe.com',
password: '123456'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
if (response.data) {
this.AuthToken = response.data.token
console.log(this.AuthToken)
axios.get('http://myurl/userdetails/:uid', {
uid: 'D123'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.AuthToken
}
}).then(response => {
if (response.data) {
// this.AuthToken = response.data
console.log(response.data)
}
}).catch(error => {
console.log('User Data response Error: ' + error)
})
}
}).catch(error => {
console.log('Login Error: ' + error)
})
I'm getting token from the first POST Login API call. I used that toke to pass into another API call as Authentication token. But I get error: Missing Authorization Headers
Found the solution:
axios.defaults.headers.common['Authorization'] = this.AuthToken;
Try to add another header. "Access-Control-Allow-Headers" : "*".

Using Axios GET with Authorization Header in React-Native App

I'm trying to use axios for a GET request with an API which requires an Authorization header.
My current code:
const AuthStr = 'Bearer ' + USER_TOKEN;
where USER_TOKEN is the access token needed. This string concatenation may be the issue as if I post this as AuthStr = 'Bearer 41839y750138-391', the following GET request works and returns the data I'm after.
axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
I also tried setting this as a global header with no success.
For anyone else that comes across this post and might find it useful...
There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms).
FYI I am using urlencoded post hence the use of querystring..
So for those that may be looking for some example code.. here is my full request
Big thanks to #swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })