How to send a request like in terminal in react? - javascript

I'm trying to send the following request in my react application
curl -H 'Client-ID: p0gch4mp101fy451do9uod1s1x9i4a' \
-X GET 'https://api.twitch.tv/helix/streams?game_id=33214'
I am able to put this exact string into my terminal and receive a response, but how exactly do I go about doing this in JavaScript or REACT?
I have tried using fetch in react but that only allows me to send a get request and that gives me an response of unauthorized access because it only takes a link, and if I send the entire thing as a string it'll just give me a 404 error because it's unrecognized.
In my terminal I can just paste in the whole string and get a valid response back. how do I replicate this in JavaScript or react?

Fetch works with any standard request method and allows for setting headers as below:
const url = 'https://api.twitch.tv/helix/streams?game_id=33214';
const options = {
method: 'GET',
headers: {
'Client-ID': 'p0gch4mp101fy451do9uod1s1x9i4a'
},
//body: JSON.stringify({name:'test'}) //example of how to have a body also
};
fetch(url, options)
.then(res=>{
if(!res.ok)
throw new Error(res.statusText);
return res.json();
})
.then(json => console.log(json))
.catch(err => {
console.error('Request failed', err)
});
for more info read the docs https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
or check this https://flaviocopes.com/fetch-api/

Related

Firebase REST API doesn't respond with common error codes using Fetch API on React Native

There were similar discussion here Firebase API doesn't respond with common error codes using Axios on react native, but guy was using Axios. I would like to use Fetch API, and hope there are similar solution using this API for current case.
The issue is when I get error from Firebase REST API statusText of response is empty. I only got status code.
If I will make same request with the same url and options using Axios I will get error description which defied by Firebase API (like TOKEN_EXPIRED, USER_DISABLED, USER_NOT_FOUND, INVALID_REFRESH_TOKEN, MISSING_REFRESH_TOKEN etc.) using console.log(error.response.data.error.message)
How I can achieve same output with Fetch API?
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: bodyString
});
if (response.ok) {
const payload = await response.json();
return payload as HttpResponse;
} else {
throw new Error(`Server error: ${response.statusText}. Status: ${response.status}`);
}
I don't know how I missed to check this.
The solution: await response.text()

Need help converting cURL command to Javascipt

I am trying to get recipe nutritional information from Edamam API. In the API docs, the cURL command is:
curl -d #recipe.json -H "Content-Type: application/json" "https://api.edamam.com/api/nutrition-details?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
I am using Axios and Javascript to try to access the API with a Post command:
import axios from "axios";
var postData = './recipe.json'
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',}
};
axios.post('https://api.edamam.com/api/nutrition-details?app_id=XXXXXXXX&app_key=XXXXXXXXXXXXXXXXXXXXX', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I receive a 400 error back. Any thoughts on what I need to do to make this work would be appreciated.
postData needs to be a string of JSON.
You appear to be passing it a string containing a filename.
You might want to read './recipe.json' with axios.get() to fetch the data from it.
In your cURL the option -d #recipe.json is sending the content of the file recipe.json
But, In your Code postData = './recipe.json', You are just passing the name instead of reading it.
First you need to read the data from recipe.json,Then you need to send it through request.

Get report for a single node/certname via PuppetDB API using ReactJS

So the API endpoint "reports" does provide this information using curl as below:
curl -X GET http://puppetserver:8080/pdb/query/v4/reports -d 'limit=1' -d 'query=["=", "certname", "node.fqdn"]'
But as I am trying to achieve this using javascript in React, that doesn't seem to work.
Something like this:
let puppetdbUrl = 'http://puppetserver:8080/pdb/query/v4/reports';
getReport = () => {
axios.get(puppetdbUrl, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
'certname': 'node.fqdn'
}
})
.then(response => {
this.setState({resultReport: response});
console.log(this.state.resultReport);
})
}
The error I get is:
400 (Bad Request). Unsupported query parameter 'certname'.
The document for puppetdb API does have these query parameters:
https://puppet.com/docs/puppetdb/5.2/api/query/v4/reports.html. Can someone please help?
I get the same error while trying to achieve the same thing using a rest client.

Getting API response payload using fetch

I am using fetch to get the API response for GET and POST requests. When an error occurs, I am able to see the status code and the text i.e, 400 Bad Request. However, there is additional information being passed that explains why the error was thrown (i.e. username did not match). I can see this additional message in the response payload via Firefox developer tool's console but I am not sure how to get it via handling the fetch response.
Here's an example request:
fetch(url, {
method: 'POST',
body: JSON.stringify({
name: name,
description: description
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + token
}
}).then(response => {
if (!response.ok) {
throw Error(response.statusText)
}
return response
})
.catch(error => {
console.log(error)
})
Any ideas? Thanks.
Thank you everyone for your suggestions.
This tutorial helped me understand what to do.
https://css-tricks.com/using-fetch/
My problem was that when there is an error, the response is not JSON, it's text. So I needed to do something like this (taken from css-tricks.com):
fetch('https://api.github.com/users/chriscoyier/repos')
.then(response => response.text())
.then(data => {
console.log(data)
});
You seem to be passing only the statusText field of the response, which corresponds to the HTTP status code (And not the response body) - for example Bad Request for HTTP response code 400.
You can read the response body using one of the methods defined on the Response object returned by the fetch API. For example, if you're expecting a JSON response body, you can have:
const onSuccess = response => {
// Do something with the response
// What you return from here will go to the next .then
}
const onFailure = response => {
// response.json() returns a promise that resolves to the JSON sent in the body
// Note that whatever is returned from here will go to the next .then
// To go to the next .catch, you can throw from here
return response.json().then(jsonResponse => console.log(jsonResponse))
}
fetch(url, {
method: 'POST',
body: JSON.stringify({
name: name,
description: description
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + token
}
}).then(response => {
if (!response.ok) {
throw response
}
return response
})
.then(onSuccess, onFailure)
.catch(err => { /* Any error thrown from the handlers will be caught here */ })
You can have a look at the Response object documentation for more details.
Based off the docs, I'd do something more along the lines of this:
const response = await fetch('http://example.com/movies.json')
const myJson = await response.json();
console.log(JSON.stringify(myJson));
Otherwise you have to do everything inside of your .then().
In regards to the additional text you are looking for, that's totally dependent on the response object, and I have no way of knowing without seeing it.
#Voxum, your answer is missing important info, like a method..and ; await is good, but remember it should be in an async function, and you dont need to use it if you "thenify" .then() as that returns the promise. from the Fetch docs, that is their basic get/HTML example. i think the OP is asking for a API call for different types of methods, which will require a more advanced setup.
The thing is with a 400 response, the server is not giving you a response message as the 404 (for example) is telling you the page is not found. Usually the only time a server will give you a response message is when you get a good (success/200). there will usually be a message at response.json() or response.text() depending on your data coming back.
after you call fetch with the url, method and any headers use
.then((response) => {console.log(response.json());}); for json and use
.then((response) => {console.log(response.text());}); for xml/text
OP has the fetch set up properly but just needs to use response.json() or response.text(). again, a 200 response can still be a "incorrect password" and this is where you'll use this. don't expect a response body on the 400/500s. good luck!

Unsupported grant type when getting OAuth token for Reddit API

I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}

Categories

Resources