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))
Related
enter image description here let headersList = {
"api-key":
"U5H4A6FcMbEuZ33LP0ACQHP0ydkXkGLLJnDfNzQzCXTpzxL8QdJ8tH7NocITeZvv",
"Content-Type": "application/json"
}
let bodyContent = JSON.stringify({
"collection":"users",
"database":"college",
"dataSource":"Cluster0",
"projection": {}
});
let reqOptions = {
url: " https://data.mongodb-api.com/app/data-tfdur/endpoint/data/beta/action/findOne",
method: "POST",
headers: headersList,
body: bodyContent,
}
axios.request(reqOptions).then(function (response) {
console.log(response.data);
})
here its giving me the cors error
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"
}
};
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
},
});
So I have to update some user info ,it works fine on postman but when I try to type it in react-native I must be doing something wrong in the body of the fetch method. In postman I set x-www-form-urlencoded and type the keys like this :
Key ----- Value
moto ----- test
and that seems to work,but when I try to do the same on my code I somehow fail at it,here is my code
updateUser(){
return fetch(url,{
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type":"application/x-www-form-urlencoded"
},
body: JSON.stringify({
moto: this.state.moto
}
})
}
)
I get 200 response which means the call works but I must be seting the parameter moto wrong somehow.
Any ideas ?
"Content-Type":"application/x-www-form-urlencoded"
should be
"Content-Type":"application/json"
form-urlencoded is way different from your body: JSON.stringify().
You'll want to use a FormData object instead:
const body = new FormData();
body.append('moto', this.state.moto);
fetch(url, {
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type": "application/x-www-form-urlencoded"
},
body,
})
APICall = () => {
fetch(‘Your http URL’, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
‘X-Auth-Token’: bearerToken,
},
body: JSON.stringify({
moto: this.state.moto
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.statuscode == 1) {
Alert.alert('Success');
} else {
Alert.alert(responseJson.message);
}
}).catch((error) => {
console.error(error);
});
}
finally fixed it by seting body to
body:
`moto=${this.state.moto}`
it appears that urlencoded headers require parameters in the form of
parameter1=value1¶meter2=value2
componentDidMount() {
return fetch(“Your URL”, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": “token”
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
})
.then((response) => response.json())
.then(function (data) {
alert(“Success”)
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
alert("error occur")
console.log('Request failed', error);
});
}
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})
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