Why does axios catch errors on successful Spotify API calls? - express

I'm having a weird and frustrationg error trying to add songs to spotify via the API.
The API call is successful and the songs are added correctly, however it returns a "TypeError: Cannot read property 'data' of undefined".
This is the code I believe should be correct.
router.post('/addSongs', async (req, res) => {
var access_token = req.query.access_token;
var playlist_id = req.query.playlist_id;
var songs = req.body.songs;
try {
var retVal = await axios({
method: 'post',
url: `https://api.spotify.com/v1/playlists/${playlist_id}/tracks`,
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-type': 'application/json'
},
data: {
uris: songs
}
});
res.send(retVal);
} catch (error) {
console.log(error.response.data);
res.status(error.response.status).send(error);
}
});
One solution I've found which makes it more frustrating is that the following change makes it work perfectly although it makes me feel horrible:
...
} catch (error) {
res.status(200).send("whatever");
}
...
I'm using Express and Netlify-lambda and I'm rather new to all of it.
Note it also works correctly and prints the error status and message when there actually is an error, and I get a "Converting circular structure to JSON" error if I only print the error

So if anyone founds this, I solved it. The issue was that axois threw an error when I tried to return the retVal variable. I think it was an empty string.
Solution:
res.send(retVal)
change to:
res.status(201).send()

Related

React Native Axios Network Error but works fine on postman client

I'm trying to get axios working on a react native project to reach a backend but I am getting the Network Error issue that I just can't seem to debug.
const searchApi = async () => {
try {
let res = await axios.get('https://product.company.com/api/documents/invoices');
console.log(res);
} catch (err) {
console.log(err);
}
}
So if I was to do a get request to the example url provided via Thunder Client or Postman Client, I get the appropriate response of
{
"status": "401 error",
"message": "Token not found."
}
But when done through axios, I seem to get a network error. I'm a little unsure how I can debug this too to get more error logs.
Try with below code:
Replace with Your URL
var config = {
method: 'get',
url: 'https://reqres.in/api/users?page=1',
headers: {
'Content-Type': 'application/json'
}
};
axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
It's not a network error but an unauthorized error. You need to pass some authenticated token in the header.

ReferenceError: DOMParser is not defined (with PubMed API)

I'm beginner from South Korea
I want to make some application with expo, which use PubMed API
It used PubMed API - eutils, and it takes request in url form, so I used 'axios'.
code is below.
Because response is like { }, and type is object
and data that I wanna parse is response.data
response.data is like
xml form document and type of it is string,
so i can extract my data with 'slice' but i want to convert respose.data into XML from.
When I use DOMParser();, It gave the following error:
ReferenceError: DOMParser is not defined
How can I solve this?
try {
axios({
method: 'get',
url: 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=11748933,11700088&format=xml',
responseType: 'json'
})
.then(function (response) {
response = response.data
console.log(response)
let parser = new DOMParser();
response = parser.parseFromString(response, "text/html");
console.log(response);
}
)
} catch (e) {
console.log(e)
}
}

How to pass formurlencoded values in post method

Here is my code
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am using Axios to fetch data from API but I am not getting response. I have tried some of the suggestions available in Stack Overflow and from web searches, but nothing helped me. I am getting error like "invalid parameters".
I also tried in Postman with the same parameter and I am getting response. What mistake am I making?
Note
Expected output: I have to get the output like status:1,msg:'success'.
What I am getting is like status:0,msg:'Invalid parameters'

Google OAuth2 redirect_uri_mismatch still occurring despite trying several solutions

I am currently trying to connect to Google OAuth with JS on server-side and am getting this error despite trying everything I could find on the web.
$('#sign-in-button').click(function () {
auth2.grantOfflineAccess().then(signInCallback);
});
function signInCallback(result) {
console.log(result)
console.log(typeof result)
if (result['code']) {
$('#sign-in-button').prop('disabled', true);
$.ajax({
type: 'POST',
url: 'http://localhost:8080/auth',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/json; charset=utf-8',
success: function (successResult) {
//todo next flow stage
console.log('Ready to proceed to next stage!')
},
processData: false,
data: JSON.stringify(result)
})
} else {
// todo handle error
console.log('An error occurred within the OAuth stage.')
}
}
The code above is what I am using on the client. The below code is the Express route for /auth.
app.post('/auth', function (req, res) {
if (req.header('X-Requested-With')) {
let oAuth2Client = getOAuthClient(); // this method uses return new OAuth2(clientId, clientSecret, redirectUrl) where redirect url = 'http://localhost:8080/link'.
let code = req.body['code'];
if (code) {
oAuth2Client.getToken(code, function (error, tokens) {
if (error) {
console.log(error.stack);
console.log('Whoops, an error occurred!')
res.send('An error occurred during the OAuth backend stage.')
} else {
console.log('No error.')
console.log(tokens)
google.options({auth: oAuth2Client})
}
})
} else {
//todo fail no code
console.log('Code failure.')
}
} else {
//todo return fail CSRF
console.log('CSRF failure.')
}
})
On cloud console, you can see my efforts of trying every possible URI under the sun!
Most strangely, in the Gaxios error, the URI is correct in the request body!
But I still get redirect_uri_mismatch
What can I try to fix this other than what I have listed below?
Add all the extra URI variants to cloud console
Use oAuth2Client.getAuthUrl() instead of my client side code
Different redirect URI (with & without slash etc.)

How to check if body in fetch POST has sent to API in react native?

I am building a react native app and got this following error. I want to send inputted message, email, and name to API, but it's not showing any result in API.
Here is the code:
fetch('localserverusingIPaddress', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
}),
})
.then((response)=> {console.warn(response.json())})
//{
// if (response.status){
// return response.json();
// }
// console.warn(response.json())
// return response.json();
//})
//console.warn(response);
//response.json()
//console.warn(JSON.parse(response))})
.then((responseData)=>{
this.showAlert();
console.warn(responseData);
return responseData;
})
.catch((error) => {
console.warn(error);
});
However, when I try to check the inputted texts in iOS
simulator, it's showing the value. It's also showing the values when I post data to API directly with postman. So I start to think that the body was failed to pass to API.
Can anyone please tell me why is this happening and how to fix this? Thank you so much, I'm facing this problem for several weeks...
First step is to make sure if your iOS simulator is actually able to make requests to your localhost or not. If it can't reach your local network, it must throw some kind of connectivity error. However, from your comment above, it seems that is not an issue.
Try this code:
let url = 'localserverusingIPaddress';
let requestObject = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
try {
let response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestObject)
});
responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error(error);
}
Try this and see what is the logged output.
Easiest way to see if the request has actually reached your API is from the API end itself. Your server must have some sort of event logging implemented. See what happens there when you make a request from Postman and compare its output with what happens when you make a request from the app.