React Native Sending Params to Server using axios - react-native-ios

I am new to React-Native
I have an issue with sending params to server in React-Native. I am using Axios for this. But when request is send to the server then I am getting error as described in catch block of the below code.
Please help me to fix this, I am attaching the response which I get from server.
Any help will be highly appreciated. Thanks
Here my code is,
axios.post('Api Url',{
params: {
'email': 'annu#gmail.com',
'firstName': 'annu',
'lastName': 'priya',
'password': '123456',
'stateId': 1,
'deviceInfo': deviceInfo
},
headers: {
'Content-Type': 'application/json',
'timezone': timeZone
}
}).then(async (response) => {
const res = response.data;
if (res.success) {
try {
// When Response is success then parse the response
this.setState(res.result);
} catch (e) {
Alert.alert('First Error Error', 'Oops! Something happened. Please try again');
}
} else {
Alert.alert('Second Error Error', 'Oops! Something happened. Please try again');
}
}).catch(err => {
// throw('Error', err);
// dispatch({type: err})
Alert.alert(err);
// Alert.alert('Third Error Error', 'Oops! Something happened. Please try again','err');
});
The Response which I am getting is, I am attaching the screenshot of the response.

Finally fixed it myself. I was sending request in not proper way.
To send params to server we can do this in following way.
axios.post('Api Url',
{
'firstName': firstNameValue,
'lastName': lastNameValue,
'stateId': stateValue,
'email': emailValue,
'password': passwordValue,
'deviceInfo': deviceInfo
},{
"headers": {
'Content-Type': 'application/json',
}
}).then((response ) => {
console.log("reactNativeDemo","response get details:"+response.data);
})
.catch((error) => {
console.log("axios error:",error);
});
Using this you can send params to server in React-Native.

Related

JSON String not getting to the server (should be easy to solve if you know express js)

I am using express js but for some reason, the server is logging an empty object {} instead of the actual JSON string that I sent. I have worked with so many other technologies like flask, this makes no sense.
Code:
function upload () {
fetch("http://localhost:8080/chat", {
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
app.post('/chat', function(req, res) {
let test = req.body;
console.log(test);
}
On the "upload" function I do not get the anything logged, and in the server, I get the an empty object {} I mentioned.
If you are to know my issue, I would appreciate help.
Thank you.
UPDATE:
Issue should be in the prontend, as sending the post request with postman works.
I think the error could be happening because you are missing the Content-Type header. You could try this:
function upload () {
fetch("http://localhost:8080/chat", {
headers: {
'Content-Type': 'application/json',
},
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
You should also make sure that in your server you are using the express.json middleware, this way:
app.use(express.json());

How do I get json data with fetch from my express server?

I’ve been trying to use fetch to get JSON data from my express server. However, it doesn’t work. I’ve tested the fetch function with JSONPlaceholder so I think my express code is the problem.
Here is my fetch code:
fetch("https://myexpressserver.com/api/example")
.then(response=> {
return response.json()
})
.then(data=> {
console.log(data.text);
})
And here is my express code:
app.get('/api/example', function(req, res){
res.json({ text: 'This is what you should get if this works' });
});
Thank you!
Instead of res.json use res.send!
app.get('/api/example', function(req, res){
res.send({ text: 'This is what you should get if this works' });
});
I also recommend to handle exception and don't use return as it will only cause error in the fetch request:
fetch("https://myexpressserver.com/api/example")
.then(response=> {
response.json();
})
.then(data=> {
console.log(data.text);
})
.catch(err =>{
console.error(err);
})
const RequestOptions = {
method: 'GET',
headers: {'Content-Type': 'application/json' },
};
fetch("https://myexpressserver.com/api/example",RequestOptions).then(Response=> Response.json()).then((data)=>{
console.log(data.txt)
})
try this because RequestOptions is important it tell what type of request we send to server

React/Express - Axios get request help needed

Trying to make an API get request from front-end (React) to back-end (Express/MongoDB) using Axios. If I use Postman to make the request it works fine (you can enter a user ID in the request body and get back an array of objects containing that user ID, which is what I want), but doing it from a front-end built in React doesn't work, I just get an empty array returned. As far as I can tell my API call from the front-end is exactly the same as the one I'm making in Postman! Can anyone shed any light on this?
This is the code making the get request from the front end:
const getActivities = async (currentUser) => {
const config = {
crossdomain: true,
headers: {
"Content-Type": "application/json"
},
body: {
"user": `${currentUser[0].id}`,
}
}
try {
const res = await axios.get('http://localhost:5000/api/activities', config)
console.log(res)
dispatch({
type: GET_ACTIVITIES,
payload: res.data
})
} catch (error) {
console.log(error)
}
}
And this is the route on the back-end handling this particular request:
router.get('/', async (req, res) => {
try {
const activities = await Activities.find({ user: req.body.user }).sort({ date: -1 })
if (!activities) {
res.json({msg: "Nothing found. Go forth and exercise!" })
}
res.json(activities).send()
} catch (err) {
res.send(err.message)
}
})
Thanks in advance!
You cannot send a request body with GET method see API AXIOS only for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'.
for example if you want to keep a GET method use params
// React
const config = {
crossdomain: true,
headers: {
"Content-Type": "application/json"
},
params: {
user: `${currentUser[0].id}`,
}
}
try {
const res = await axios.get('http://localhost:5000/api/activities',config)
console.log(res.data)
}catch(err){
...
}
// Express
router.get('/', async (req, res) => {
console.log(req.query.user)
}

Getting service error when came back from Facebook handover in node js bot V4

I have written below code to handover the control to page inbox.
var options = {
method: 'POST',
url: process.env.FBgraphPassThreadURL,
qs: { access_token: process.env.FBTOKEN_V4_NAMES },
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/json'
},
body:
{
recipient: { id: stepContext.context._activity.from.id },
"target_app_id": process.env.HandoverTargetAppId,
"metadata": "String to pass to secondary receiver app"
},
json: true
};
var response;
await rp(options)
.then(function (parsedBody) {
console.log('--- status---', parsedBody);
response = parsedBody;
})
.catch(function (err) {
// POST failed...
console.log('----from catch ---', err);
console.log('----from catch ---', err);
});
console.log('callcenterhandover response-->', response);
return stepContext.endDialog();
Now customer successfully handover to page inbox-main folder. when I mark the customer as done then customer come back to bot and bot executing onConversationUpdate event and onMembersAdded event. Hence I consider onConversationUpdate event and written below logic.
this.onConversationUpdate(async (context, next) => {
this.dialog.initialDialogId =** 'handOverWelcomeDialog' **;
await this.dialog.run(context, this.dialogState);
await next();
});
Now handOverWelcomeDialog will run and display some welcome message to user and ends the dialog.
Not sure where am doing the mistake and why am getting below error after 1 minute from Bot.
[onTurnError]: Error: {
"error": {
"code": "ServiceError"
}
}
How can I fix this service error?
Any suggestions please ASAP. Much appreciate. Thanks in advance.

Google Recaptcha not working with axios

I am encountering an error while trying to verify my recaptcha witch axios
try{
let result = await axios.post(
'https://www.google.com/recaptcha/api/siteverify',
{
secret: '6LcarRkTAAAAAPDNrruugUg1fJqOJnH-uvVa5KIL',
response: response
},
{
headers: {
"Content-Type": "application/json"
}
});
let data = result.data || {};
if(!data.success){
throw({
success: false,
error: 'response not valid'
})
}
}catch(err){
console.log(err);
throw err.response ? err.response.data : {success: false, error: 'verifyCatpcha Error'}
}
I am always getting the error
{ success: false,
'error-codes': [ 'missing-input-response', 'missing-input-secret' ] }
I tried it with postman and it works fine. Something wrong with my header?
You need to add one more key to your request: secret. The error message is caused by missing response and secret parameters when sending POST request.
UPDATE: The POST params in the doc are not JSON, they must be passed as query string. That's why the error says it's missing both missing-input-response and missing-input-secret
axios.post(
`https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${response}`,
{},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
},
},
);
Reference: Doc
I managed to solve it be adding params.
I will accept Ryan Wus answer cause it is basically the same with different writing.
try{
let result = await axios({
method: 'post',
url: 'https://www.google.com/recaptcha/api/siteverify',
params: {
secret: '6LcarRkTAAAAAPDNrruugUg1fJqOJnH-uvVa5KIL',
response: response
}
});
let data = result.data || {};
if(!data.success){
throw({
success: false,
error: 'response not valid'
})
}
}catch(err){
console.log(err);
throw err.response ? err.response.data : {success: false, error: 'captcha_error'}
}
https://stackoverflow.com/a/48083886/5426839
The POST params in the doc are not JSON, they must be passed as query string. That's why the error says it's missing both missing-input-response and missing-input-secret
Not opposite to the highest answer, just shorter syntax:
axios.post('https://www.google.com/recaptcha/api/siteverify', undefined, {
params: {
secret: RECAPTCHA_V3_SECRET,
response: recaptchaToken
}
})

Resources