How to add a BearerToken to React API Requests? - ruby-on-rails

newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!

You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

Related

NativeScript-Angular - POST formdata to Wordpress ContactForm7 API

Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values ​​in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}

Response Isn't Converting To JSON

I'm trying to take info from a React form and post it to my Rails database, but I get an error "unexpected token '<' at position 0" which means my response is still HTML and not JSON.
Here's my code:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Is there a reason why it's not converting to JSON?
Additionally, I don't seem to be able to drop debugger into my code, or at least in this function - do I need to import it or something?
I'm thinking that your server is sending you back HTML and then you are trying to parse it in response.json()
use a try/catch in this block:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => {
try {
return response.json()
} catch(error) {
console.error(error);
}
})
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}

Observable with POST call in Angular2

I am using Angular2 in my application, And I saw advantages of using Observable while calling http calls. But somehow I am not able to make call when I am using Observable for POST requests, But it's working while GET request. If I use subscribe method, then POST is working.
Below is my code,
using Observable,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<boolean> {
console.log("Data = ", JSON.stringify(breakoutUploads));
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/breakout/InsertUploads", JSON.stringify(breakoutUploads), options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Using subscribe,
Adding(breakoutUploads: Uploads) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http
.post('/breakout/InsertUploads', JSON.stringify(breakoutUploads), options)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
My API,
[HttpPost]
public bool InsertUploads([FromBody]BreakoutUpload breakoutUploads)
{
return true;
}
What mistake I am making while using observable in POST call ?
Not sure what I changed, But it starts working with below code,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(Configuration.Url_AddBreakoutsManually, JSON.stringify(breakoutUploads), options) // ...using post request
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

How to use 'fetchData' method in react native with authentication header and body with POST method for iOS

In my current iOS project I need to fetch data from api call with POST method along with login credentials(userName & Password) as authentication header in react native javaScript file.
Can someone Please help me on that.
refernce screen shot
Just set the fetch method to 'POST', add in headers and body as key-value pairs and process response. Here is an example.
var bodyMap = {};
// fill in the body map with keyvalue pair
fetch(POST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': authValue,
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyMap)
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
//process response
})
.catch((error) => {
console.warn(error);
});

Using curl command for react native to fetch api

I'm trying to use the petfinder APi for an app I'm creating and following the API documentation which can be found here : https://www.petfinder.com/developers/v2/docs/#developer-resources.
It gives the command : curl -d "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}" https://api.petfinder.com/v2/oauth2/token
Im trying to translate this for react native and used the following code:
getAdopt1 = async() => {
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}"
}),
}).then((response) => response.json())
.then((responseJson) => {
let res = JSON.stringify(responseJson)
console.log("Response: "+res)
return responseJson;
})
.catch((error) => {
console.error(error);
})
}
However I get the following error:
Response: {"type":"https://httpstatus.es/400","status":400,"title":"unsupported_grant_type","detail":"The authorization grant type is not supported by the authorization server.","errors":[{"code":"unsupported_grant_type","title":"Unauthorized","message":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","details":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","href":"http://developer.petfinder.com/v2/errors.html#unsupported_grant_type"}],"hint":"Check that all required parameters have been provided"}
What am I doing wrong here ?
You are sending a JSON request but what the API expects is a Form-Data request.
Try with something like this:
var form = new FormData();
form.append('grant_type', 'client_credentials');
form.append('client_id', '{CLIENT-ID}');
form.append('client_secret', '{CLIENT-SECRET}');
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: form,
}).then(response => {
console.log(response)
}).catch(error => {
console.error(error);
})

Resources