How to use post method in react native? - reactjs

constructor(props) {
super(props);
this.state = {text: this.props.navigation.state.params.text,
name:this.props.navigation.state.params.name};
}
manage = () => {
Alert.alert('done')
Actions.reset('mainScreen');
fetch("http://ip/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.props.navigation.state.params.name,
text:this.props.navigation.state.params.text
})
})
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
i want to do this
when i press in button go to manage function
and post the text and the name to my api i dont know how can i pass them
its give me this error :
network request failed
any help please

I recommend you to use axios to make network requests.
Installing:
npm i -S axios
Performing a POST request:
import axios from 'axios';
axios({
url: 'http://ip/api/confirm',
method: 'post',
data: {
name: this.props.navigation.state.params.name,
text: this.props.navigation.state.params.text,
},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
if (resp.status == 200){
var respBody = await resp.json();
console.log('Fetch Todo response '+respBody);
}
API in separate file
export async function manage(userId,ApiKey,query,query1) {
var url ="http://www.example.com/getdata";
const params = {
search:query,
searches:query1
};
var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const requestOptions = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
},
'body': formBody
};
requestOptions.headers["userid"] = userId
requestOptions.headers["apikey"] = ApiKey
try {
var resp = await fetch(url, requestOptions);
return resp;
}
catch (err) {
console.log("Request Failed: " + err);
return err;
}
}

Related

How to return const from react axios function in another file? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a file with form to call a submit function in another file.
And I would like to retrieve the response of the request to use it in file 1.
How can I do that ?
First file form.js
handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
newAppartement(newAppartementTableau);
const messageRequest = ??;
Second file data.js
export function newAppartement(newAppartementTableau) {
axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
You are not returning anything in your function, you're just making an axios call. To solve this add this :
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
in your first file
newAppartement(newAppartementTableau).then(res => console.log(res.data).catch(e => console.error(e));
You need to wait for the function to finish using await async:
async handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
const response = await newAppartement(newAppartementTableau);
and in second file you can return a promise like this:
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}

Bad Request React Axios 400

Can Anyone tell me why I am having this error??
the error is status code 400 bad request
This could be on the server?
I am new with react
handleSubmit(event, _success, _error) {
event.preventDefault();
var data = {
FriendlyName: this.state.FriendlyName,
full_name: this.state.full_name,
email: this.state.email,
};
const config = {
method: 'post',
url:
'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers',
headers: {
Authorization:
'Basic QUM1MmNiOTIxNGQwY2ZmMjA4NjBiZDdjMTQ5Y2Q4NjBlNTpmODRmOWJiOGFlZjI4MWFmZDY2NGY4NTY1OGYwNzJhOA==',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(() => {
console.log('data', data);
if (Object.keys(data).length > 0) {
if (typeof _success === 'function') _success(data);
} else {
if (typeof _error === 'function')
_error({ error: 'Não houve nenhum retorno.' });
}
})
}
Try backticks instead of apostrophe url:'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers'
const config = {
method: 'post',
url:
'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers',
headers: {
Authorization:
'Basic QUM1MmNiOTIxNGQwY2ZmMjA4NjBiZDdjMTQ5Y2Q4NjBlNTpmODRmOWJiOGFlZjI4MWFmZDY2NGY4NTY1OGYwNzJhOA==',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};

AXIOS get request failed 400 React Native

I am trying to make an axios get request to this endpoint, but I am keep getting this error " [Error: Request failed with status code 400]".
clikk = () => {
console.log('saasdasdl');
var user = 'reflect-user';
var pass = 'user1Pass';
let dta = JSON.stringify({
username: 'test.admin',
password: 'password',
emailAddress: 'test#gmai.com',
});
const headers = {
'Content-Type': 'application/json',
Authorization: 'Basic ctesmtVmbGVjdC11c2VyOnVzZXIxUGFzcw==',
'Access-Control-Allow-Origin': '*',
accept: 'application/json',
};
// var bytes = utf8.encode(user + ':' + pass);
// var authorizationBasic = base64.encode(bytes);
axios({
method: 'get',
url: 'http://IpOfServer:8080/api/v1/user/getUser?all=true',
headers: headers,
data: qs.parse({
username: 'test.admin',
password: 'password',
emailAddress: 'test#gmai.com',
}),
})
.then((res) => {
//const nameList = res.data;
//this.setState({nameList});
console.log(res);
})
.catch((error) => console.log(error));
};
However same request is working in POSTMAN so API may not be involved ish? I've also tried to AXIOS example provided by POSTMAN but I am getting the same error.
var data = JSON.stringify({"username":"test.admin","password":"password","emailAddress":"test6#gmai.com"});
var config = {
method: 'get',
url: 'http://IpOfServer:8080/api/v1/user/getUser?all=true',
headers: {
'Authorization': 'Basic cmVmbGVjdC11c2VyOnVzZXIxUGFzcw==',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Thank you.

React-Native image upload

Is it possible to upload file (images) to server with react-native using FormData? Tried to use it like this:
var data = new FormData();
data.append('file', file);
console.log(JSON.stringify(data));
var id = 5;
fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id,{
method:'POST',
body: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;',
},
});
For React, FormData works as expected but for React-Native not working.
I have also tried (used in react - working)
const data = fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id, {
credentials: "same-origin",
method:'POST',
body: dataval,
timeout: 1000000000,
});
But nothing works,
In the back-end server, I am upload using
var d = require('domain').create()
d.run(function safelyUpload () {
var file=req.file('file').upload({dirname: path.resolve(sails.config.appPath, folder),
}, function whenDone(err, uploadedFiles) {
if (err) return res.serverError(err);
else{
sails.log.debug('Complaint File data : ' +util.inspect(uploadedFiles, {showHidden: true,depth: null}));
}
});
});
Is there any other ways
Here is example to upload image using Fetch API
const photo = {
uri: user.profilePicture,
type: 'image/jpeg',
name: 'photo.jpg',
};
const form = new FormData();
form.append("ProfilePicture", photo);
fetch(
URL,
{
body: form,
method: "PUT",
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + user.token
}
}
).then((response) => response.json())
.catch((error) => {
alert("ERROR " + error)
})
.then((responseData) => {
alert("Succes "+ responseData)
}).done();
Credits https://stackoverflow.com/a/36649457/5315786

Return data from method in object

I have been trying to figure this one out and I'm not getting how to return the data to another method and call it so that I don't have to statically add the data into my request. I keep getting undefined data on my B2C method when I run it for the data returned from this.O_Auth. Any clues?
let obj = {
O_Auth(key, secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
request(
{
uri: "https://randomurl",
method: 'GET',
headers: {
"Authorization": auth
}
},
(err, res, body) => {
if (err) {
return err;
} else {
// console.log(body);
let response = JSON.parse(body);
let res = JSON.stringify(response.access_token)
return res;
}
}
);
},
B2C(params) {
console.log("Random " + this.O_Auth('first', 'second'));
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + this.O_Auth('first', 'second'),
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}
}
Ended up figuring out the asynchronous nature of JavaScript meant I was requesting data that was being evaluated later so I used a promise to get the data and output it first before using it in a subsequent promise that outputs the body. Changed the first request to request promise (rp) that returns the options that will be needed for that promise in the second method.
let obj = {
O_Auth(Key, Secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
let options = {
uri: "https://randomurl",
headers: {
"Authorization": auth
},
json: true
};
return rp(options)
},
B2C(param1, param2, param3...) {
this.O_Auth('first', 'second'))then(response =>{
let token = response.access_token;
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}).catch(error => console.log(error));
}
}

Resources