I'm running following js-code. But I keep getting an error from Spotify Webpage (saying there was some sort of error).
credentials is a base64 encoded string of client_id and secret.
The curl-command works just fine:
curl -X "POST" -H "Authorization: Basic *credentials*" -d grant_type=client_credentials https://accounts.spotify.com/api/token
The js-code doesn't work properly..
I guess it's pretty easy, but I'm not that good in js (sorry!).
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {'Authorization': 'Basic *credentials*'},
body: 'grant_type=client_credentials'
})
.then(response => response.json())
.then(data => {
console.log(data);
});
As specified in the Spotify Authorization guide the body has to be application/x-www-form-urlencoded so just add this header:
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization': 'Basic *credentials*',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: 'grant_type=client_credentials'
})
.then(response => response.json())
.then(data => {
console.log(data);
});
Related
I would like to connect to REST API that uses a token Bearer.
I try the JS code below :
sessionStorage.setItem('MCToken',
JSON.stringify('123456')
);
let datastructuresAPI = () => {
let token = JSON.parse(sessionStorage.getItem('MCToken'));
let header = new Headers({
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
});
let response = fetch('https://mon_url',{
method: 'POST',
headers: header,
body:JSON.stringify({
"methodName":"connect",
'grant_type': 'client_credentials',
"serviceName":"ConnectionService"
}),
'x-frame': 'same-origin',
mode: 'no-cors'
});
console.log(response)
}
datastructuresAPI();
But I can’t connect, I have these message (the first is the result of the console.log)
Thank you for your help
Fetch function is an async function and you should wait it.
fetch(...)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
For the other result (401) are you sure that your REST API waits token with Bearer {token}? It could be only {token}.
I have a fetch POST that returns a Token, which I then need to use for a fetch GET to extract the data I need. The GET with token works in CURL via:
curl -X GET \
https://myCorp.csod.com/services/api/Recruiting/JobRequisitionDetails/Ad\
- H 'Authorization: Bearer myToken' \
- H 'cache-control: no-cache'
I want to do similar with JavaScript. I have the following code to POST (to get the token) and then use it (data.access_token) in a GET
fetch(proxyUrl + 'https://myCorp.csod.com/services/api/oauth2/token', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
}
}).then(response => response.json()).then(data => {
let headers = {
"cache-control": "no-cache"
}
fetch(
proxyUrl + "https://myCorp.csod.com/services/api/Recruiting/JobRequisitionDetails/Ad",
{
method: "GET",
headers: {
'Authorization': 'Bearer ' + data.access_token,
'cache-control': 'no-cache',
}
}
)
.then((response) =>console.log(response))
.then((data) => console.log(data));
});
"ProxyUrl" in this case is a proxy for CORS. It will print out "undefined" and in the console it will log "bad request"
I assume something in my code is wrong, anyone that can help?
I have a .netcore web API application with several endpoints and I have a simple UI built to access an endpoint with a button click using javascript fetch API.
fetch('api/Sessions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(callData)
})
.then(response => response.text())
.then((response) => updateResponse(response))
.catch(error => console.error(error));
}
Now the API endpoint in the controller is authenticated with API-KEY, [ServiceFilter(typeof(AuthorizeKey))] I can no longer access the endpoint from my UI. How can I change the HTML/javascript code in order to send the post request from my UI to the authenticated endpoint?
Thanks
Please correct me if I'm wrong.
fetch('api/Sessions', {
method: 'POST',
headers: {
'X-API-KEY': 'apikey',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(callData)
})
.then(response => response.text())
.then((response) => updateResponse(response))
.catch(error => console.error(error));
Building a Django Rest Framework. when I user 'curl' to call the API with a valid token it works:
curl -viL -H "Authorization: Token 65c38dfe0c910b727197683aebdcc1c67c1b7aa3" http://127.0.0.1:8000/api/habit/
The same API call via my javascript call, fails and Django see it as an anonymous user and errors out.
fetchHabits: function() {
console.log('Token '+this.authToken.token);
fetch('http://127.0.0.1:8000/api/habit/?format=json',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token '+this.authToken.token
}
})
.then(response => response.json())
.then(json => this.habits = json)
},
I have proven that the right token is sent and received. I am assuming because CURL works that the Django code is working, so that the bug is in the header on the Javascript side.
Can anyone help please?
There was a missing component in the HTTP header, it needed to have "cedentials: 'included'"
The final header was :
fetch('http://127.0.0.1:8000/api/habit/?format=json',{
method: 'GET',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
'Authorization': 'Token '+this.authToken.token
},
credentials: 'include'
})
I am posting the details of user in api ,using the access token in header which i got in sign up but getting this error --> Unexpected end of JSON input. My code is
postNameToApi()
{
console.log("inside post api");
fetch('https://MyPostApi', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer'+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
},
body: JSON.stringify({
dob:'1992-04-18',
gender: 'femanino',
is_professional:true,
is_referee:false
})
}).then((response) => response.json())
.then((responseData) => {
console.log("inside responsejson");
console.log('response:',responseData);
//this.setState({response:responseData});
}).done();
}
This is because your response is not in json format. Space is missing between Bearer and your token, i think this will solve your issue.
'Authorization':'Bearer '+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
Try your api call with postman first.