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));
Related
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
I want send multipart/form-data to spring server with some information. but i dont know this is right way.
a.push({ name: 'file', filename: this.state.fileName, data: RNFetchBlob.wrap(this.state.uri), desc: 'triptriptrip'});
this.setState({
images : a
})
});}
RNFetchBlob.fetch('POST', 'https://675c8a26.ngrok.io/appServer/postUpload/1', {
'Content-Type': 'multipart/form-data',
},this.state.images
)
i expect spring server get 'desc' information but server cannot access to 'desc'. how to access that data?
If you want to use formdata, use it like this.
RNFetchBlob.fetch('POST','https://675c8a26.ngrok.io/appServer/postUpload/1',{
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
[
{ name: 'file', filename: this.state.fileName, data: RNFetchBlob.wrap(this.state.uri), desc: 'triptriptrip'},
]).then((response) => response.json())
.then((res) => {
console.log(res);
}).catch(err => {
console.log(err)
})
});
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.
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.
I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
)
which i get in my glassfish server doing something like
HttpServletRequest request;
request.getParameter('mail');
I'm moving my application in react native so i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: 'mail=bob#test.com',
})
and i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but neither of these worked, i'm deseperately having request.getParameter('mail') == null on server side.How can i do ?Note : i don't want to change the way the server handles things.