Code:
let response = await fetch(
`https://discord.com/api/guilds/877414872068001853/members/[user id]`,
{
method: 'PUT',
access_token: `Bearer [user access code]`,
headers: {
"Authorization": `Bot [bot token]`,
"Content-Type": "application/json"
}
}
);
console.log(response);
The bot is in the server that I want the user to join
The guilds.join oauth scope is set
Error:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'https://discord.com/api/guilds/877414872068001853/members/522503261941661727',
status: 400,
statusText: 'Bad Request',
headers: [Headers],
counter: 0
}
}
Thanks to #user15517071
I had the access_token not in the body, and also the "access token" i was using was just the redirect token from discord oauth so i needed to use the actual access Token discord provides you after getting the users details, and it works.
{
method: 'PUT',
body: JSON.stringify({
access_token: `Bearer User_AccessToken`,
}),
headers: {
"Authorization": `Bot Bot_Token`,
"Content-Type": "application/json"
}
};
Related
I am trying to write function to Sign in user with Email and Password.
Using Axios and firebase rest API.
So this is how Axios instance looks like, really simple right? ...
const authUrl = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${DATABASE_SECRET}`;
const baseURL = "https://beauty-wonderland-e913c-default-rtdb.firebaseio.com";
export const getAxios = (token = null) => {
const config = {
baseURL: baseURL,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers":
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
},
timeout: 10000,
};
if (token !== null) {
// config.headers.Authorization = `Bearer ${token}`;
config.baseURL = authUrl;
config.withCredentials = true;
}
let instance = axios.create(config);
instance.interceptors.request.use(
(request) => {
return request;
},
(error) => {
console.log("axios error: ", error);
return Promise.reject(error);
}
);
instance.interceptors.response.use((response) => {
return response;
});
return instance;
};
This code works fine, flexible and can send any kind of request, but when it comes to authentication, there is problem with sending user data: email and password.
const loginHandler = async () => {
const response = await getAxios("/").post("", {
body: JSON.stringify({
email: "example#example.com",
password: "password",
returnSecureToken: true,
}),
});
const outPut = processResponse(response);
console.log(outPut);
}
so as i guess There is problem with this part
{
body: JSON.stringify({
email: "a#a.com",
password: "123456",
returnSecureToken: true,
}),
});
}
if fetch function works this way
fetch(
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPasswordkey=${DATABASE_SECRET}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "example#example.com",
password: "password",
returnSecureToken: true,
}),
}
);
why do axios gives following error:
XMLHttpRequest at ... from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please note other get and post request with axios works, and alo authentication works with fetch, only axios shows such an error, please post additional resourses to learn more about firebase rest API and Axios usecases.
This is how error looks like
The baseURL in the axios instance returned by "getAxios" function is https://beauty-wonderland-e913c-default-rtdb.firebaseio.com and not the Auth REST API url. It should be authUrl instead. While in fetch you have hard-coded the URL so the URL is correct for sure.
Edit:
Remove those extraneous headers. You just need content-type as per the docs. I got the same CORS error when I had those.
const config = {
baseURL: baseURL,
headers: {
"Content-Type": "application/json",
},
timeout: 10000,
};
I am implementing the Search function using spotify api.
However, if you request get to api now, 400 will be returned.
I want you to help me with this.
axios({
headers: {
"Authorization": `Bearer ${token}`
},
method: 'GET',
url: 'https://api.spotify.com/v1/search',
qs: {
q: value,
type: 'album',
},
}).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
const options = {
method: 'GET',
url: `https://api.spotify.com/v1/search?q=${value}&type=album`,
headers: {
'Authorization': `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
}
}
axios(options).then((res)=>console.log(res))
.catch(err=>console.error(err))
In React, this is working:
let token = localStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
Everything is ok. It gives success.
But in React Native (AsyncStorage), it gives wrong token error (403):
let token = AsyncStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
In console.log(token), everything seems great. I can see my token. It also works well in Postman.
According to the docs:
Returns:
Promise resolving with a string value, if entry exists for given key,
or null otherwise.
Promise can also be rejected in case of underlying storage error.
Since it returns a Promise, you should get the token using .then() or async/await:
async function doRequest() {
let token = await AsyncStorage.getItem("token");
// do request
}
I want to know whoever sees this post in the future that Axios did not send my headers in React-Native. In such a case, maybe you should try fetch.
#Rafael's answer was also great.
fetch("http://localhost/api", {
method: "post",
headers: new Headers({
"x-auth-token": `${token}`,
"Content-Type": "application/json",
}),
body: {
body
},
});
I am getting network error while doing axios.post request.
axios.post({
method:'POST',
url:'http://xxx.xxx.xxx.xxx:6310',
withCredentials: true,
auth: { username: 'username',
password: 'password'},
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'},
data :{"jsonrpc":"1.0", "method":"liststreams","params":[]}
}).then(function(response) {
console.log('res ------- ',response)
}).catch(function(error) {
console.log('error =',error)
})
Thanks,
I am doing a POST request to auth api with a username and password and expecting a token in the response.
fetch('https://auth.entranceplus.in/auth', {
credentials: 'omit',
method: 'POST',
mode: 'cors',
body: JSON.stringify({
"username": this.userName.value,
"password": this.password.value
}),
headers: new Headers({
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Data-Type': "json"
})
}).then(function (response) {
if (response.status === 200) {
return response.json();
} else if (response.status === 503) {
this.setErrorMessage('Failed to check-out license');
} else {
this.setErrorMessage('Incorrect Username or Password');
}
}.bind(this)).then(json => {
localStorage.setItem('username', this.userName.value);
localStorage.setItem('accesstoken', json.access_token);
});
As you can see in the image Request URL is http://localhost:3000/?username=dfbfdjhgfk&password=76895jfjg
My question is why the request not getting posted to https://auth.entranceplus.in/auth