AXIOS get request failed 400 React Native - reactjs

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.

Related

Connection with Basic HTTP authorization with email and password body application/x-www-form-urlencoded with axios

I am trying to create a new session with axios following this documentation:
https://www.traccar.org/api-reference/#tag/Session/paths/~1session/post
This is my code, I have really tried everything without results
const sessionurl = 'http://31.220.52.187:8082/api/session';
const params = new URLSearchParams();
params.append('email', 'admin');
params.append('password', 'admin');
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios
.post(
sessionurl,
{
withCredentials: true,
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
},
},
{
params
},
)
.then(function (response) {
console.log('Authenticated');
})
.catch(function (error) {
console.log('Error on Authentication');
});
It should be something like this:
const params = new URLSearchParams();
params.append('email', 'admin');
params.append('password', 'admin');
axios.post(sessionUrl, params);
You might need to also add a header.

How can I send a String to a web service using POST request (react native)?

Is it possible to send a String to a PHP web service using a POST request (react native)? I only find some JSON POST requests like the following:
functionName = async() => {
const response = await fetch('http://localhost/webservice.php', {
method: 'POST',
mode: 'no-corse',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
searchQuery: 'something',
})
})
const myData = await response.json();
this.setState({data: myData});
}
How can I transform this to send a String (like just one word) instead of a JSON String?
Something like
functionName = async() => {
const response = await fetch('http://localhost/webservice.php', {
method: 'POST',
mode: 'no-corse',
headers: {
Accept: 'application/json',
'Content-Type': 'text/plain'
},
body: 'Your text'
})
const myData = await response.json();
this.setState({data: myData});
}

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,
};

How to use post method in react native?

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;
}
}

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

Resources