Make Discord Request With NodeJS (Change Vanity Discord) - javascript

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)});

Related

Discord api get guild

I'm trying to fetch my guild info from discord API
fetch('https://discord.com/api/guilds/772037458996101140', {
headers: {
authorization: 'bot Nzc******zNjYzOTAz.GPwhCV.rhIcH****5R8ZS-cIo4MjPcBVxO6wYsUXhY'
},
})
.then(result => result.json())
.then(response => {
console.log(response);
})
.catch(console.error)
only reciving 401 (unauthorized)
i tried changing "bot" to "BOT", "Bot", "Bearer"
and doing authorization using access token from Oauth2
The problem lies in how the Authorization header has been specified. The correct way specify headers would be:
fetch('https://discord.com/api/guilds/772037458996101140', {
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': 'bot Nzc******zNjYzOTAz.GPwhCV.rhIcH****5R8ZS-cIo4MjPcBVxO6wYsUXhY',
},
})
.then(result => result.json())
.then(response => {
console.log(response);
})
.catch(console.error)
Hope this helps.
Edit
Also added crendentials and withCredentials based on this answer.
I was sending http request from front-end and when i moved it to back-end or just used python test file it worked using : Authorization: 'Bot <TOKEN>'
not sure why but it works how it should mby somebody can explain ?

React how to get accessToken?

I want to send a post with fetching. But I get 401 error: www-authenticate: Bearer error="invalid_token".
I am using Userfront.accessToken() but It did not work.
How can I get accestoken for bearer authentication?
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
}).then((res) => res.json());
};
Note:
console.log(`Bearer ${Userfront.accessToken()}`);
Bearer [object Object]
Can you try this? I see this from https://userfront.com/guide/auth/
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
JSON.stringify(Userfront.accessToken()) please stringify that object to understand what is going on there then if there is accessToken returning from that function put that string.
I just realized in the doc;
To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from
the Authorization header and verify that it is valid using the public
key found in your Userfront dashboard.
https://userfront.com/guide/auth/
fetch('https://api.example.com', {
method: 'GET'
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
});
Thank you all for your answers.
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
In this application, token gets a different name.
When I look from inspects, I use it and it works!

JavaScript (Discord Oauth2) 400: Bad Request

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!

Unable to get access token from json rsponse

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));
}

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