POST request to Spotify API saying no token - javascript

I am getting this error message when I am trying a POST request:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
The thing is I am passing in an access token by making a headers variable and assigning it to the headers for the post request like this:
const headers = {
Authorization: `Bearer ${accessToken}`
}
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
'headers': headers,
method: 'POST',
body: JSON.stringify({'name': name})
This fetch request is the one giving me the error I stated above. How can I fix this?
Headers object picture right before the fetch request
Here is the link to the GitHub: https://github.com/aoljaca/jamming
This code is in the src/utils/Spotify document
Thanks!

I tried running your code but it threw a different error before it it was able to reach that part of your program.
One possible debugging strategy is making sure the headers variable is still defined and includes the access key before returning the fetch request. Just print it to console before running that particular fetch. If it goes out of scope at some point in your promise chain then it could be null.
I'd also suggest using headers: headers instead of 'headers': headers.

Related

Get authorization token from headers into fetch reactj

I am using fetch in my react project to fetch data from an API which is authenticated using a token and my login end-point in the postman return the token in authorization header, you can see
and this's my login funtion in reactjs project
async login(dataLogin) {
const response = await fetch(`${API_URL}/login`, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: dataLogin
});
const data = await response
console.log(response.headers);
console.log(response.headers.Authorization);
console.log(response.headers.get('Authorization'));
return data;}
you can see that response.headers.authorization return undefined and
response.headers.get('Authorization') return null.
and you can see in my browsers' Network panel
please anyone know how to get the authorization token from the headers?
When you are trying to login using API, then you should receive data i.e. Authorization token or anything else in the response of call.
Check what is the response you're getting when you called an API, it should probably be like
response.data
First you need to check the same in Postman.
To access value of response header server must return header name in Access-Control-Expose-Headers header. Without it Authorization is inaccessible in browser.
response.headers.get('Authorization')
Edit:
Since you are getting null, consider that:
The Authorization header is usually, but not always, sent after the
user agent first attempts to request a protected resource without
credentials.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
Therefore, instead of using postman, in order to see the response header, use the browsers' Network panel.

React Native - Request with URL that includes credentials

So I have to make requests to various urls with different domains which contains credentials
I've successfully managed to send one like this:
const resp = await fetch(`my-url-here`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(my-key-here)}`
},
body: JSON.stringify(data)
})
However this works only for one domain while on the other I keep getting
[TypeError: Network request failed] on Android
[SyntaxError: JSON Parse error: Unexpected identifier "undefined"] on iOS (while executing the .json() method; I think the request is successful but with an empty response)
Every call on these domains work correctly using PostMan/ThunderClient
Any idea how to solve this?
Please share how you are processing response seems like request works fine but somehow there is an error while parsing the data into JSON.
invalid data contains in response which is not able to parse into JSON.

why data is undefined in post method

I m using react js app and I try to post data to my api , but I got undefined insert for one time .
instead of 'url' I have working url.
this is my post method's code:
senddata(){
if(!this.formvalidation())
{
try{
let resulte = fetch('url',{
method:'post',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
ID:this.state.code,
Blod:this.state.blod,
Allergic:this.state.allergicdescription,
Chronic:this.state.chronic_description
})
});
alert("post");
}catch(e){
alert("not post")
}
}
}
thanks.
You said mode:'no-cors' so any attempt to do anything which requires permission from CORS will fail silently.
Setting 'Content-type': 'application/json' requires permission from CORS.
Presumably, your server side code is not parsing the request body as JSON since the Content-Type header doesn't say it is JSON.
Since there is no parsed data, all the properties you want to read from the JSON will be undefined.
Don't use mode:'no-cors' if you want to POST JSON.

Simple GET method for DailyMotion API with Google AppScript is returning 503 error. How do I get it to work consistently?

Whenever I make the API request with GET method, it is returning a 503 error from Google AppScript. However, this same request is successfully getting response consistently when run from Postman or the web-browser.
The AppScript code returns a JSON response out of the blue at first call and all consecutive calls return with the error 503. This server response is showing up specifically to the AppScript code here.
The detailed error message is as follows:
Exception: Request failed for https://api.dailymotion.com returned code 503. Truncated server response: Gone. (use muteHttpExceptions option to examine full response) (line 24, file "DailyMotion")
function dailymotionArtist() {
var artistchannelID = 'x24dh63';
var requestOptions = {
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
'muteHttpExceptions': true,
method: 'GET'
}
var finalResponse2 = UrlFetchApp.fetch('https://api.dailymotion.com/user/' + artistchannelID + '?fields=followers_total%2Cviews_total', requestOptions);
Logger.log(finalResponse2.getContentText());
}
A 503 error message is generally representative of a server being unable to respond to a request temporarily, and is not normally a representation of an incorrect request - see description of the 503 code.
I would always suggest trying a request using Postman or another HTTP Client to test the API isn't just down temporarily before debugging a 503 code.

Console log raw data of a failed Axios get request

I would like to make an Axios get request to a private server running Flask.
In case there is an internal error in the back-end it returns an response object and an error code.:
response_object = {
"Success": False,
'error': err.message
}
return response_object, 400
The served response_object should be accessible the front-end (React.js).
axios
.get(`http://127.0.0.1:5000/data`, {
data: null,
headers: { "Content-Type": "application/json" }
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error.toJSON());
});
I would expect the error to include the response object. If the URL is accessed manually in the browser the error data is visible. If there is no error in the back-end the get requests works properly.
After googling for some time I found some issues that might relate to the mentioned problem. (That is why empty data is passed in the a get request).
https://github.com/axios/axios/issues/86
https://github.com/axios/axios/issues/86
Please note that I am self taught so I might miss something obvious here. Thank you all and all the best.
I'll copy/paste my comment here so other can easily see the answer for the question
if it's a 400 status code that it's throwing (you can confirm by using the Network tab in your browser), it will fall into the catch block, the only concern is the toJSON() call... just do a simple console.log(error.message) to check if you ever get there...
I leave you a simple example so you see the catch in action
more information:
in Axios, the response text is in response.data
if you are receiving a JSON, the response.data will be automatically parsed
you do not need to pass data: null as that's the default behavior, and it's not used in a GET call (you won't pass a body in a GET call)

Categories

Resources