AXIOS : Send Authorization header returns Error 401, Authorization Header missing - vue.js

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" : "*".

Related

Axios formData with image is sending empty array

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

my react-native app fail to send body in POST request to backend url

As i am trying to send my data in form of body in backed url as in backed i have made something if it dont receive body it will send sucess: false, msg: haven't received body else sucess: true, msg: jwt token as if i make request from post man with same data it's working but sending via. native app it fails to send.. any help will be helpfull
As 1st request is from postman and 2nd from my app
const handleLogin = (Enrno, Pass) => {
setError(null);
setIsLoaded(false);
setItems([]);
fetch(config.url + "/login", {
method: "POST",
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
"enrno": Enrno,
"password" : Pass
})
})
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
alert(items[0].msg);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
};
I think you need to put these to headers, not header.
Accept : 'application/json',
'Content-Type' : 'application/json'
So, it should look like this.
fetch(config.url + "/login", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
enrno: Enrno,
password : Pass
})
})

Using Axios GET with Authorization Header in vue App

I'm trying to use axios for a GET request with an API which requires an Authorization header.
here is my current code
My current code:
data () {
return {
listings: [],
AuthStr : 'Bearer ' + JSON.parse(localStorage.getItem('token')),
}
},
created () {
axios.get(`url`, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
it shows me 403 error I don't know why.
There are several ways to to add header to request.
For a single request:
let config = {
headers: {
Authorization: value,
}
}
axios.get(URL, config).then(...)
you need to call data().AuthStr to get your token there is a typo.
Your created function will be
created () {
axios.get(`url`, { 'headers': { 'Authorization': data().AuthStr } })
.then((response) => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
It should be:
axios.get(`url`, { 'headers': { 'Authorization': this.AuthStr } })
You are using JSON.parse when getting the value for AuthStr. JSON.parse returns an object. Try removing it and if you are using the correct Auth token, it should work.

Reading post data from react-native

I have this fetch() method that is sending data from my react-native app to a laravel method
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
//let res = await response.text();
if (response.status >= 200 && response.status < 300) {
console.log(response);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
I can receive the data using this method
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData);
//parse_str($postedValue, $output);
return response()->json([
'name' => $postedValue,
'route' => $postedValue
]);
}
and attempting to return the just posted data. The posted data looks like this
12:35:07 PM:
{"type":"default","status":200,"ok":true,"headers":{"map":{"connection":["Keep-Alive"],"content-length":["54"],"content-type":["application/json"],"set-cookie":["XSRF-TOKEN=eyJpdiI6IlF1NWlLOE9rVCtlUXNpYzBFSTV0c0E9PSIsInZhbHVlIjoiNWtGenprRmJOYTVsc2dQRjNrcmpxZXhWeFZRd1NZSzdiOWFKUUZTZmJJaEN6U0RnbW9uOVZ4bGUrV2ZMYUlIb0NQNHFrT1pCWXB0dnlwTjhPWm56ZWc9PSIsIm1hYyI6IjU3NDJkNWE5M2U4YmIwNTUwNzhkZTM4ZTRlNDc5OTZhNjczYWEyODU0OGNmN2ViNDdkYTM4YjdjY2U1ZWE1ZmYifQ%3D%3D;
expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/,
laravel_session=zqcMrXeuwwGpEsR8Jh2WakDg0cdqLod4QsfMnfcd; expires=Fri,
09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/;
HttpOnly"],"access-control-allow-methods":["GET, POST, PUT, DELETE,
OPTIONS"],"access-control-allow-origin":["*"],"cache-control":["no-cache,
private"],"server":["Apache/2.4.18
(Ubuntu)"],"keep-alive":["timeout=5, max=100"],"date":["Fri, 09 Jun
2017 09:35:07
GMT"]}},"url":"http://no-tld/androidLogin","_bodyInit":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}","_bodyText":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}"}
I now want to access the returned email from my native-react app.
console.log(response.email); returns null. How can i access the returned email value in react native?
Try below fetch call,
React-native log-android //Android
or react-native log-ios // IOS
use to see response data or error details
fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: 'chesterfield#gmail.com', password: '123456'})
}).then((response) => response.json())
.then((responseData) => {
console.log("responseData : " +responseData); // fetch response data
}).catch((error) => {
console.log("error : " +error); // error
});
I fixed it this way
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://198.74.51.225/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
let userData = JSON.parse(res);
console.log(userData.email);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
Just to be sure of the post data returned, you can modify the posted data in the server side and return it using this function
//Android Login
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData,true);
$token = rand(400,7833);
return response()->json([
'email' => $token."_".$postedValue['email'],
'password' => $postedValue['password']
]);
}
For this to work, i had to also allow cors using this middleware
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
and i used it in my route like this
//Android
Route::group(['middleware' => ['cors']], function() {
Route::post('androidLogin', 'Auth\LoginController#androidLogin');
});
Hope that helps someone trying to post or get from a react-native app.

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 } })