I am working on implementation of strava in my website. I am new to JavaScript and I am not understanding whether I am doing it correctly or not. My problem is I am unable to get access token from JSON response. I don't know why. Please Help me.
the resonse what I am getting
code
<script>
const auth_link = "https://www.strava.com/oauth/token"
function getActivites(res){
console.log('response2',res.json());
const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
fetch(activities_link)
.then((res) => console.log(res.json()))
}
function reAuthorize(){
fetch(auth_link,{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxxx',
refresh_token: 'xxxxx',
grant_type: 'refresh_token'
})
})
.then(res => {
var response = res.json();
var access_token = response.access_token;
console.log('response',access_token)
// getActivites(res)
})
}
reAuthorize()
</script>
I am getting access token as undefined
function reAuthorize() {
fetch(auth_link, {
method: "post",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: "55077",
client_secret: "801a8541e8ae55cffee584a48c5bb6a233dea9a0",
refresh_token: "08342cdf3250da9e0d1b53303fa40faf0d05965d",
grant_type: "refresh_token"
})
}).then(response => response.json())
.then(data => console.log(data));
}
Related
I'm trying to make members join a server using oauth2.
Whenever I use the api/guilds/${guild}/members/${user} endpoint, I get this error
{ message: '400: Bad Request', code: 0 }
The code I used:
let gid = '868120277077360660';
let usid = '591950387112574988';
fetch(`https://discord.com/api/guilds/${gid}/members/${usid}`, {
method: 'PUT',
access_token: `Bearer ${accessToken}`,
headers: {
authorization: `Bot ${botToken}`,
"Content-Type": "application/json",
},
payload: {
access_token: `Bearer ${accessToken}`,
}
})
.then(result => result.json())
.then(async reo => console.log(reo));
I'm using node-fetch as fetch, in the code. I'm using NodeJS.
I tried many solutions, but none of them worked, it would be great if you can guide me through!
Thank you!
const response = await fetch(`https://discordapp.com/api/oauth2/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
redirect_uri: redirectURL,
grant_type: 'authorization_code',
code: code,
}),
});
When I run the above code, it returns with { error: 'invalid_grant' } and I do not know why. Are there any fixes to this? Thank you.
Don't you also need to send the scope param as per the docs:
const data = {
client_id: 'your client id',
client_secret: 'your client secret',
grant_type: 'authorization_code',
redirect_uri: 'your redirect uri',
code: accessCode,
scope: 'the scopes',
};
fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(res => res.json())
.then(console.log);
You need to send your body as URLSearchParams(data).
You also need to add this at the top of your code:
const fetch = require('node-fetch');
Check this new link:
https://discordjs.guide/oauth2/#oauth2-flows
I fixed it, all I had to do was to use querystring instead of JSON.
I'm making a bot that can change url code with a request, but i've tried something, and it's only returning the current invite code
My code:
fetch('https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"test458"
})
})
.then(res => res.json())
.then(json => { console.log(json)})
And it's returning
{ code: 'cherrys', uses: 0 }
I just want to change the code, but idk how i can do that, and when i try with a user token it say
401: Unauthorized
Can someone help me with that?
The prefix Bot on the Autorization header is only for Bots, if you want to use a user token, you need to use Bearer prefix instead of the bot ones.
fetch('https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url', {
method: 'POST',
headers: { 'Authorization': `Bearer ${client.token}`, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"test458"
})
})
.then(res => res.json())
.then(json => { console.log(json)});
I’ve this axios request which is running ok I got http 200
import {AxiosResponse} from "axios";
const axios = require('axios').default;
const qs = require('qs');
//First query
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
//Second query (the only different is the scope )
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': ‘exe:crud’}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
Now I want to run two request in parallel and get the results which is response.data (the data I sent to the request / headers etc)
I’ve tried with but the response I got is like the request , I don’t get the tokens/data? Any idea
How can I use this two request in parallel ?
axios.all([{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
},
{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'exe:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}]).then(axios.spread((...responses: AxiosResponse[]) =>{
const aToken = responses[0];
const bToken = responses[1];
}).catch(function (error: any) {
console.log("Error: " + error);
});
If there is a better way , please let me know
Btw, if I run this two post request separated everything is working fine
You need to provide promises to the axios.all not their config objects.
axios.all([
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'run:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}),
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'exe:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
})
]).then(axios.spread((...responses: AxiosResponse[]) => {
const aToken = responses[0];
const bToken = responses[1];
}).catch(function(error: any) {
console.log("Error: " + error);
});
Keep in mind though that the axios.all and axios.spread are deprecated.
Use Promise.all directly
how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})