How to pass formurlencoded values in post method - react-native

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'

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.

VueJS and Axios POST- $_POST empty on server side

I am at witts end with axios/vue currently, hoping someone can see something I am missing.
I am using axios documentation and doing a basic post.
axios({
method: 'POST',
url: 'myurlhere',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
The api is absolutely hit, I am logging it on the server side. The console log on the axios side does not throw any errors. I am printing out the $_REQUEST variable on the server side just to see what is coming through and the $_POST is empty. The console log does show the returned array but post is empty.
<?php
$data=array('worked'=>true,"data"=>$_REQUEST);
echo json_encode($data);
?>
If i use $_GET variables they work. Post does not though. what am I doing wrong???

Why does axios catch errors on successful Spotify API calls?

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()

Getting issue on API call where I am returning response like Unauthorized

I am trying to call an api using axios. The required params, headers I am passing correctly but on api hit I am returning response as api error: {"message":"Unauthorized"}. I tried with too many solutions like using bearer, jwt token, I also changed API calling library to fetch but still no success.
axiosGetWithHeaders('url',
{
param1: 'emailid'
},{
Authorization : 'token',
ContentType: 'application/json',
}
).then((res) => {
console.log("RESPONSE", JSON.stringify(res))
})
.catch((error) => {
console.error('api error: ' + JSON.stringify(error));
console.error('api error: ' + JSON.stringify(error.response.data));
});
Try with axios:
axios.defaults.headers.common["Authorization"] = accessToken;`enter code here`

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.