Connecting to an API from my localhost throws http/2 error - javascript

I am connecting to an API. It works fine when I use Postman. But When I use the code generated from postman in my angular project ( on my localhost ) I cannot perform the requests. I get an error: net::ERR_HTTP2_PROTOCOL_ERROR instead of an error code in my browser. The fetch code I use:
let code = params.get('code');
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Host", "login.eveonline.com");
myHeaders.append("Authorization", "Basic NThmYjljMGEwMWM5NGI1ODhkNmUzYzVlMTQ4NjYyYjQ6eVRUUzFGRTdUtZTzBNZkpCZw==");
let body = {
grant_type: "authorization_code",
code: code
};
fetch("https://login.eveonline.com/v2/oauth/token", {
method: 'POST',
headers: myHeaders,
body: JSON.stringify( body )
})
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Related

fetch Microsoft bearer token not working from the browser

I am trying to implement that
https://learn.microsoft.com/en-us/graph/auth-v2-service?view=graph-rest-1.0
Its working from node and postman but not the browser
This was copied from postman
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Cookie", "fpc=blabl; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "bla-bla");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "bla-bla");
urlencoded.append("grant_type", "client_credentials");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://login.microsoftonline.com/blabla/oauth2/v2.0/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Any ideas what i should include or omit in the fetch request?
The code above will not work in the browser. This code above needs to be executed on the server (you are using "client secret").
If you want browser-only (SPA) authorization, consider using PKCE authorization flow instead.
Other than that, the code looks okay, there is nothing wrong with it.

Accessing in Chrome POST response body from Cloudflare Worker

I am trying to read a response from a Cloudflare Worker API, I have not set anything sepcial about it and in Postman the request works as expected. I am guessing I am missing some header but I am not sure which one or even if that is the reason reading the reponses body is not working in browser.
This is how I fetch the data:
const url = `${process.env.SOME_URL}/v1/method?token=${TOKEN}`
const headers = new Headers();
headers.append("Content-Type", "application/json;charset=UTF-8");
const requestOptions = {
method: 'POST',
redirect: 'follow',
mode: 'no-cors',
body: JSON.stringify(body),
headers
// referrerPolicy: 'no-referrer',
};
return fetch(url, requestOptions)
.then(async (response) => {
// no body to be parsed
return response.json()
} )
.then(result => console.log(result))
.catch(error => console.log('error', error));
Looking forward to your answers, thank you.
This behaviour is due to the no-cors config of the fetch-api.
For more details read about opaque requests here:
What limitations apply to opaque responses?

Post request to the firebase cloud functions gives error 500

I have a POST request to the Cloud Functions on Firebase. When I'm trying to make a request, I get a CORS policy error. Ok, I set mode: 'no-cors' and get Failed to load resource: the server responded with a status of 500 ().
Here is the code
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Accept", "application/json");
let raw = JSON.stringify({
"description": "Test item",
"email": "testemail#gmail.com"
});
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
mode: 'no-cors',
redirect: 'follow',
};
fetch("https://someURl.cloudfunctions.net/someRequest", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The code is copied from Postman
Any ideas?
As confirmed by jaba, the issue was on server side. Also, same has been documented here.

Error while sending a message to twitch chat with Javascript StreamElements

I am getting a 400 error when trying to send a message to twitches IRC chat with StreamElements API.
Here is my code so far I know it is incorrect but I don't know how to pass the message to twitch in order for it to accept it. I am learning ajax and will be learning jQuery in the future however if the help could please be in vanilla JS.
var data = {"message": "test"};
var token = "secret"
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(data);
XMLHttpRequest is a bit old library to make HTTP request.
Consider using the new fetch API in (vanilla) JavaScript.
var data = { message: "test"};
var token = "secret"
await fetch('https://api.streamelements.com/kappa/v2/bot/5eab1a7fc644de5b0169703c/say', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})

How do you make an API request using browser fetch with token auth

I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})

Categories

Resources