How to do a post request in ReactNative with formData - react-native

I need do a post request with fetch
like this
in Postman.
And what I've tried :
let formData = new FormData();
formData.append('username', String(username));
formData.append('password', String(password));
let init = {
method: 'POST',
header:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
}
fetch(url, init)
It's successful in Postman but failed with fetch that return a 400 error with no param. Hope some helps , thanks
So I changed my code
var details = {
'username': '123',
'password': '123',
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
let init = {
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}
fetch(url, init)
But get a same error
console the formBody:
username=123&password=123
My headers key was wrong ,that was the fault
should be:
let init = {
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}
instead of
let init = {
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}

Status code 400 means you sent a bad request, i.e. the server expected something else.
In this case you're sending raw multipart/form-data (the first option in Postman), while you say you are sending x-www-form-urlencoded in your headers.
Since you'll want to use the latter according to your Postman screenshot, you have to send your body in x-www-form-urlencoded format.

Related

Vuejs: axios; Passing custom header in POST method

We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.

How to send Base64 code to webservice webservice?

I try to send my base64 code to my webservice :
this is my base64 :
I send like this :
let collection= {};
collection.base64 = this.state.data;
fetch('url', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify({'JsonWithImage': collection.base64 }), // data can be `string` or {object}!
})
However, as you see it gives error message which is in image. I think because of size of image but I am not sure. Any idea about this ?
Via this post there is a javascript function window.btoa() which encodes data to Base64 string which may work for you.
let collection= {};
collection.base64 = this.state.data;
fetch('url', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify({'JsonWithImage': window.btoa(collection.base64) }), // data can be `string` or {object}!
})

How to fetch Webservice which takes string parameter?

I try to fetch webservice method. However, it takes string. How can I send string parameter to webservice ?
I tried like this :
fetch('url/MethodName', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json',
}),
})
where should I put string parameter ?
by mozilla
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
send Json data as parameter
You can do that with fetch, but try to use Axios for making http requests
https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index

Getting false response and empty data array in react-native post save data to server

I am trying to save a simple registration form to server using fetch but getting response false.
apiDataSave = () => {
fetch('<myapi>', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name : "abc",
no : "1234567890",
password : "123",
email : "abc#gmail.com"
})
})
.then(function(response) {
return response.json();
})
.then(function(data) {
alert(`response json is: ${JSON.stringify(data)}`)
})
}
I am getting alert as follows:
response json is: {"status":false,"data":[]}
The expected result alert is:
response json is: {"status":true,"data":"1"} // number of records entered in database
The problem was that the Content-Type was not 'application/json' but following:
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
I got the answer here:
stackoverflow answer

HttpClient or Http POST with header request not hitting to the server

I'm trying to issue an http request to validate user and in response i need to get token issued by the server.
this ajax call working fine
$.ajax({
url: '/token',
'data': JSON.stringify({ Id: "test", Password: "test" }),
'type': 'POST',
'processData': false,
'contentType': 'application/json',
success: function (response) {
console.log("token =" + response);
},
});
But i need it in angular so i tried below two methods but none of them worked.
1st
let header = new Headers({ 'Content-Type': 'application/json', 'processData': false});
let options = new RequestOptions({ headers: header });
this.http.post('/token', JSON.stringify({ Id: "test", Password: "test" }), options)
.map(response => {
debugger;
console.log("token =" + response);
});
2nd
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
what is wrong with them.
I am using Dotnet Core 2.1 and angular 5
Please help me to solve this issue.
Your methods are observables.
In order to send the request and get the result, you need to subscribe to them.
This is an example of the 2nd method.
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}).subscribe(response => {
console.log("token =" + response);
});