How to fetch Webservice which takes string parameter? - react-native

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

Related

my react-native app fail to send body in POST request to backend url

As i am trying to send my data in form of body in backed url as in backed i have made something if it dont receive body it will send sucess: false, msg: haven't received body else sucess: true, msg: jwt token as if i make request from post man with same data it's working but sending via. native app it fails to send.. any help will be helpfull
As 1st request is from postman and 2nd from my app
const handleLogin = (Enrno, Pass) => {
setError(null);
setIsLoaded(false);
setItems([]);
fetch(config.url + "/login", {
method: "POST",
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
"enrno": Enrno,
"password" : Pass
})
})
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
alert(items[0].msg);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
};
I think you need to put these to headers, not header.
Accept : 'application/json',
'Content-Type' : 'application/json'
So, it should look like this.
fetch(config.url + "/login", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
enrno: Enrno,
password : Pass
})
})

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 get access token from api in react native

I am using react native and i want to get the access token from api which is created in django using oAuth 2 authentication
i am passing all the details which are required but i do not know why i am getting error of unsupported grant type
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
'scope': 'read Write'
})
})
.then((response) => response) <----tried response.json() but giving same error of grant type
.then((responseData) => {
console.log(responseData);
})
My expected result is i want access token should display
and what i am getting is
Response {type: "default", status: 400, ok: false, statusText: undefined, headers: Headers, …}
headers: Headers {map: {…}}
ok: false
status: 400
statusText: undefined
type: "default"
url: "http://MyUrl"
_bodyInit: "{"error": "unsupported_grant_type"}"
_bodyText: "{"error": "unsupported_grant_type"}"
__proto__: Object
please help
thanks in advance
tried response.json() but giving same error of grant type - this is answer from Your oauth server.
response.json() transform your response data into json decoded string.
Change Your code to this:
let formData = new FormData();
formData.append('grant_type', 'password');
formData.append('username', 'MyUserNameSettedInApi');
formData.append('password', 'PasswordSettedInApi');
formData.append('client_id', 'MyClientId');
formData.append('client_secret', 'MyClientSecret');
formData.append('scope', 'read Write');
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
});
Install qs library
npm install qs
Import it in your app and then you'll be able to send it.
Use qs.stringify as shown below
fetch('http://localhost:8888/o/token',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;'
},
body: qs.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
})
})
I also got that same issue of "{"error": "unsupported_grant_type"}" for that, I just pass all the body parameters directly without using JSON.stringify({}); It works for me, find the example code below.
body: 'grant_type=password&username=MyUserName&password=MyPassword'
you need to update the body section only.
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=password&username=MyUserName&password=MyPassword'
})
.then(res => res.json())
.then(token => console.log(token))
.catch(err => console.error(err));
Hope this will help you.

react-native fetch - request body - Unexpected EOF

in my react-native application, I'm trying to make fetch request with body. But, I get error message of unexpected EOF. Actually, the request is made, I mean I can see through backend logs that request is sent, whereas, right after the request, it shows error message.
Here is my fetch method.
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("SEND_SMS RESULT: ",responseJson);
})
.done();
here is the error screen I get.
I would say that it fails on this line: response.json()
Are you sure that your response is a valid JSON?
Try testing the response with Postman or add .catch(e => console.log(e)) before done();
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.text())
.then((responseJson) => {
const resposeJson2 = responseJson.length ? JSON.parse(responseJson) : {};
console.log("SEND_SMS RESULT: ",responseJson2);
})
.done();
Your server is returning null instead of error and unfortunately response.json() cant operate on null response
you can research briefly on it the keywords are "Handling null response from api"