Getting API authentication key error with PublicAPI - javascript

I'm new to the FetchAPAI. For my first API project, I'm currently using the ClimatIQ API and following the steps in their Quickstart guide. Even if I've already signed up and received an authentication key from them, I keep getting the ff error from them:
POST https://beta2.api.climatiq.io/estimate 400
{error: 'invalid_request', message: 'Error parsing the request body.'}
Take note in the guide, the code is in Curl, and I did my best trying to convert that code into a fetchAPI request on JavaScript.
const fetchData = async (url) => {
await fetch(url, {
method: "POST",
headers: { Authorization: "Bearer MY_API_KEY" },
data: {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
},
//body: JSON.stringify(data),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");
From time to time, it also shows a "header is not defined" even if I already put in the authentication key they gave me in the "MY_API_KEY" part of my codebase. Is this an error with their server?

try this:
const data = {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
};
const fetchData = async(url) => {
await fetch(url, {
method: "POST",
headers: {
Authorization: "Bearer MY_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");

Related

cannot get XSRF-TOKEN from cookie in nextjs (Reactjs)

I create a login form using Nextjs and backend with Laravel 8, I generate an XSRF-TOKEN in Laravel then set it on cookie, I can see the token inside inspect element> application tab> cookie section, but I can't set it on my fetch request to make my login, I using redux to store my data such: products, auth, cart and etc
AuthAction.js code:
export const LOGIN_AUTH = "LOGIN_AUTH";
export const LOGOUT_AUTH = "LOGOUT_AUTH";
export const HandleLogin = (data) => {
return async (dispatch, getState) => {
const getCsrf = await fetch("http://localhost:8000/sanctum/csrf-cookie");
if (!getCsrf.ok) {
throw new Error("Faild to set csrf token");
}
console.log("getCsrf", cookie.load("XSRF-TOKEN"));
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw Error("Login faild");
}
try {
const responseData = await response.json();
console.log("login", responseData);
dispatch({
type: LOGIN_AUTH,
user: responseData,
});
} catch (err) {
console.log("Login err", err);
throw err;
}
};
};
after console.log("getCsrf", cookie.load("XSRF-TOKEN")); nothing happened.
what do I do wrong in my code?
cookie screenshot:
request response:
Use axios instead of fetch.
Example:
axios
.get("http://localhost:8000/sanctum/csrf-cookie", {
withCredentials: true,
})
.then((response) => {
axios("http://localhost:8000/api/app/user/login", {
method: "post",
data: data,
withCredentials: true,
})
.then((response) => {
console.log("login", response.data);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
// handle error
console.log(error);
})
.then(() => {
//
});
Since your next.js and laravel apps are on different origins, you need to set fetch to explicitly send cookies.
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
credentials: 'include'
});
You can read more about the credentials property in the MDN docs
Also, you can read the cookie in the front-end if it's http-only cookie.
Also, don't forget to set up Cross origin resource sharing in your backend app.

Spotify Web API / Next.js: Only getting data from one end-point

I'm pretty new to working with API's, and I'm currently trying to fetch some data from the Spotify API in a Next.js website.
The problem is that the only end-point that gives me any data is the 'top-tracks': (https://api.spotify.com/v1/me/top/tracks), all the other end-points I've tried gives this error:
Request failed FetchError: invalid json response body at https://api.spotify.com/v1/me/player/recently-played reason: Unexpected token U in JSON at position 0
This is the function I'm using to fetch data from the API:
const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
export default async function handler(req, res) {
const response = await fetch(TOKEN_ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: querystring.stringify({
grant_type: "refresh_token",
refresh_token,
}),
})
.then((response) => response.json())
.then((data) => {
const access_token = data.access_token;
return fetch(`https://api.spotify.com/v1/me/player/recently-played`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
},
});
})
.then((response) => response.json())
.catch((err) => {
console.error("Request failed", err);
});
return res.status(200).json(response);
}
(First getting the access token, using clientId and secret from env-variables, then fetching data from API using said token)
Any idea of what I'm doing wrong here? All help is greatly appreciated :)
Also:
I've added the necessary scopes, so I should have permisssion to get the data!

Cloud Function returns undefiend when using POST

I am trying to send the param name in the Cloud Function managed by Firebase using POST method, I've read quite a few documentation, and no matter what I try it always returns undefined. Also is it safe to use this for sensitive data?
Client-Side
fetch(`https://<<APP-NAME>>.cloudfunctions.net/addCardForExistingCustomer`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
JSON.stringify(body: {'name': 'Name'})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(err => console.error(err));
Server-side (Firebase Cloud-Functions)
exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {
let name = await request.body.name
response.json({
response: `${name}`
})
})

Get response.data from fetch() as variable to use in React-Native

I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.
const getFlights = async () => {
const token = await getAsyncData("token");
instance({
method: "get",
url: "/api/flights/",
headers: {
Authorization: `Token ${token}`,
},
})
.then(function (response) {
// console.log(response.data.results); // shows an array of JSON objects
return response.data.results; // I've also tried response.data.results.json()
})```
I just want the response returned as a variable that I can use to populate a FlatList component in RN.
const FlightListScreen = () => {
const [list, setList] = useState([]);
const flights = getFlights(); // currently returns as a promise object
Thank you for your help.
I think you have to store the response object directly to the json method. And then with that response you can store it to the variable
.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
})
you are sending token without a bearer. Concrete your token with bearer like this
headers: {
Authorization: "Bearer " + token,
},
and another thing is your response class are not right this should be like this
.then((response) => response.json())
.then((responseJson) => {
API will Resopne here....
}
this is a complete example to call API with Token
fetch("/api/flights/", {
method: "GET",
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setState(responseJson.VAlue);
})
.catch((error) => {
alert(error);
});

CORS issue while trying to get data from a clip on Vimeo using the api/oEmbed

I am using fetch to get the data.
Like so:
getClipMetadata = (url) => {
const endpoint = 'http://www.vimeo.com/api/oembed.json';
fetch(`${endpoint}?url=${encodeURIComponent(url)}`, {
method: 'get',
cache: 'no-cache',
mode: 'cors',
headers: new Headers({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
})
.then((response) => { return response.json();})
.then((res) => console.log("async response received", res))
.catch((err) => console.log("ajax error -> ", err))
}
So the error I get is this:
Response for preflight is invalid (redirect)
I thought it looked quite simple from Vimeo's developer page.
What am I doing wrong?
The endpoint is 'https://vimeo.com/api/oembed.json' rather than 'http://www.vimeo.com/api/oembed.json' and the headers I was sending were causing problems too.
So the final working code looks like this:
getClipMetadata = (url) => {
const endpoint = 'https://vimeo.com/api/oembed.json';
fetch(`${endpoint}?url=${encodeURIComponent(url)}`, {
method: 'get',
cache: 'no-cache',
mode: 'cors',
})
.then((response) => { return response.json();})
.then((res) => console.log("async response received", res))
.catch((err) => console.log("ajax error -> ", err))
}

Categories