Bad Request React Axios 400 - reactjs

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

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.

react native upload image with axios

I have this data
came from react-native-image-picker
data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kb
fileName: "77677.jpg"
fileSize: 67542
height: 600
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/77677.jpg"
type: "image/jpeg"
uri: "content://media/external/images/media/18584"
width: 399
__proto__: Object
and am try to set this data in object type #FromData to upload #img
var binaryDataInBase64 = new FormData();
binaryDataInBase64.append('file', {
// data: response.data,
uri: 'file://' + response.uri,
name: 'MMM.jpg',
type: response.type
})
console.log('=======================>', binaryDataInBase64)
axios.post(
'https://danskeclouddemo.com/api/file',
{ file: binaryDataInBase64 },
{ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data' } }
).then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
and this is BackEnd Postman Working good Postman collection
//======================
//======================
Edit
Some people talk about the problem from react native version after 0.61.5
in this link issues
Your form data must be like that.
formdata.append('file',{
uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
name: 'test',
type: 'image/jpeg' // or your mime type what you want
});
Then
axios.post('/users/profilepic', formdata, config).then((res) => {
console.log(res.data);
return res.data;
});
Rather using, axiom use fetch simple, approach to upload, image
this.setState({imageLoading:true})
const credentials={
userId:this.state.userId
}
try {
let response = await fetch(
'url',
{
'method': 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: createFormData(source, credentials)
}
);
if (response.status == 200) {
response.json().then(data => {
switch (data.status) {
case 200:
break;
}
});
}else {
this.setState({imageLoading:false ,isLoading:false})
}
} catch (error) {
this.setState({imageLoading:false,isLoading:false})
console.error(error);
}
const createFormData=(image,body)=>{
var data = new FormData();
data.append(image, {
uri: Platform.OS === "android" ? image.uri : image.uri.replace("file://", ""),
name: `dummy${Date.now()}.jpg`,
type: 'image/*'
})
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return 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.

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

How to add Function in POST Headers

The target is sending a POST request with Autorization header contains token.
It's function:
export function authHeader() {
// return authorization header with jwt token
let user = JSON.parse(localStorage.getItem('user'));
if (user && user.token) {
return { 'Authorization': 'Bearer ' + user.token };
} else {
return {};
}
}
Here is async function send to server:
export async function submitToServer(values){
try{
let response = await fetch('http://localhost:50647/fund/submitfund', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type' : 'application/json',
authHeader()
},
body: JSON.stringify(values),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
How can I add authHeader() to headers in POST to correctly authorize this request?
Use ... spread operator like, ...authHeader(). Your authHeader function returns an object { 'Authorization': 'Bearer ' + user.token } or {}. What you want is to merge it to the object you attached with the headers key, so ... operator is the correct tool here.
So your code will be:
export async function submitToServer(values) {
try {
let response = await fetch('http://localhost:50647/fund/submitfund', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...authHeader()
},
body: JSON.stringify(values),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}

Resources