How work https api in React-native-android? [duplicate] - https

This question already has answers here:
React-native POST request in android over https return network error
(3 answers)
Closed 2 years ago.
in reactnavtive app we work with 'http' for url in axios and evry things is ok , now we change 'http' to 'https' but Apis failed ... and app don't work ... why ? please help me.

This call will work for both HTTP and HTTPS
Try this example for POST CALL
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
Try this example for GET CALL
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});

i found answer this question , my url was : 'https://185.305.1.13/index.image.png' , we add domin for images , and url chaghed :'https://image.com/index.image.png'... and revso

Related

Authorization failed on a fetch request to the Brawl Stars API

I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!

Unauthorized response with valid token

I get unauthorized as response on every request after login successfully
this is some of my code (let me know if you need to see anything else):
Data provider on ionic
this.storageProvider.getToken().then(results => {
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + results,
'Accept': 'application/json',
})
};
});
public getTodayReservations() {
//all reservations (not todays only)
let _url = this.url + '/guides/reservations/all';
return this.http.get(_url, this.httpOptions);
}
an this the config of my laravel api routes:
Route::prefix('v1')
->group(function () {
Route::post('login', 'Api\UsersController#login');
Route::middleware('auth:api')
->prefix('guides')
->group(function () {
Route::get('/show', 'Api\UsersController#show');
Route::get('/reservations/today', 'Api\ReservationsController#today');
Route::get('/reservations/all', 'Api\ReservationsController#allRes');
});
});
Request Headers:
Accept: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI.....
Content-Type: application/json
Origin: http://localhost:8100
Referer: http://localhost:8100/
As you can this.storageProvider.getToken() return a promise and not a token.
try something like this :
export class HttpService {
private httpOptions;
constructor(){
this.storageProvider.getToken().then(results => {
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + results,
'Accept': 'application/json',
})
};
});
}
Check response of this.storageProvider.getToken(), usually it has access_token key which you are supposed to use in order to authroize your app so your code, not the full promise so your code will be like:
this.storageProvider.getToken().then(tokenObject => {
private httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + tokenObject.access_token,
'Accept': 'application/json',
}
)
};
});
Of course, in your case, it might be some other key, that is why you should have a look at this.storageProvider.getToken() first and only send the actual access token when sending Authorization header.

Laravel & Vue.js API file uploading doesn't work

I have a problem with file uploading on my Laravel&Vue.js website using API
I get - 500 Server Error "SyntaxError: Unexpected token < in JSON at position 0"
I'm trying to create new value in my database, for this I use pop up form with image uploading and other fields like username, email, phone etc.
I've tested my API via Postman - it works fine, but when I try to create this directly on my website - it desn't work
you can check a function which must create new value(startup) in DB:
createStartup() {
fetch('/api/startup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: JSON.stringify(this.new_startup),
})
.then(res => res.json())
.then(res => {
$('#createStartUp').modal('hide');
alert('New Startup Created!');
// this.fetchStartups();
})
.catch(err => console.log(err));
}
I think the issue in Headers (I didn't use any Headers in Postman), when I tried to not use any Headers - it didn't wok too, also O tried to use Content-Type with bypass and unfortunately it didn't work
Also I think it must be helpful - how I get image in vue.js:
HTML:
<input id="upload_create" class="file-upload_input" type="file" #change="onFileSelected" >
JS (Vue.js):
onFileSelected(event) {
this.new_startup.startup_logo = event.target.files[0];
}
Thanks a lot guys for any ideas and helps!
You need to pass your data as form-data. Here is how I managed to send a file upload via Vue.js:
createStartup() {
let formData = new FormData();
formData.append('file', this.new_startup.startup_logo);
formData.append('anythingElse', JSON.stringify(this.someVariable);
// ... etc
fetch('/api/startup', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData,
})
.then(res => res.json())
.then(res => {
$('#createStartUp').modal('hide');
alert('New Startup Created!');
// this.fetchStartups();
})
.catch(err => console.log(err));
}

Issue in AJAX request in reactjs

I am trying to develop an application using reactjs as front end framework and laravel 5.6 as back end framework. I am trying to send AJAX request like below
import Auth from '../services/Auth';
var address_data = {
name :'foysal',
address :'foysal',
telephone_no:'foysal',
email :'foysal',
}
fetch('http://127.0.0.1:8000/api/addresses/store/',address_data, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + Auth.getToken(),
},
body: JSON.stringify()
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
I am getting below errors
Try changing your fetch request to initiate POST action verb like this
fetch('http://127.0.0.1:8000/api/addresses/store/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + Auth.getToken(),
},
body: JSON.stringify(address_data)
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

React Native getting response 400 when post to oauth/token using laravel passport

I am trying to login through oauth/tokens from my React Native project. I have tested with POSTMAN When i send the data from axios it works well. But when i try to send from my app it gives me Error: Request failed with status code 400
my code is :
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: {
client_id : '2',
client_secret : 'secret',
grant_type : 'password',
email : this.state.userEmail,
password : this.state.userPassword
}
})
.then((response) => {
console.log(response.data);
})
I've solved the problem in this way:
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: 'client_id=2&client_secret=secret&grant_type=password&email=' + this.state.userEmail+'&password='+this.state.userPassword
})
.then((response) => {
console.log(response.data);
})
Seems Axios have some problem to process the data in json format.
If you use Webpack you must also configure the proxy.

Resources