react native fetch call (es5) returning undefined response. Here is the code of my fetch call.
body = {"username":"Gdgf","password":"dfgdfgdfg","remember":""}
var promise = new Promise(function(resolve, reject) {
fetch(`${FINAL_URL}users/login_app?app=1&submit=1`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// 'content-type': 'application/x-www-form-urlencoded',
// 'content-Type': 'multipart/form-data'
},
body: JSON.stringify(body),
})
.then(response => response.json())
.then(responseData => console.log('responseData', responseData)) // console output is --> responseData []
.catch(err => {
reject(err);
});
});
attaching the screnshot of postman too, to show that api is working.
Most of the time this problem occurs when you don't call your end point correctly. As you said in the comments, in the console log of ${FINAL_URL}users/login_app?app=1&submit=1 you missed the www, which makes the response undefined. If you still have a problem please delete new Promise section from the fetch.
I hope I could help.
Can you try changing the following line:
then(responseData => console.log('responseData', responseData))
to
then(responseData => console.log('responseData', JSON.stringify(responseData)))
What is the console output now?
Related
When I call API I am getting below error in response. please find below is code and error message.
TEST RESPONSE:
{
"responseData": {"limit": ["Limit is required"],
"module_type": ["Module type required"],
"section": ["section value \"liveability || investment || recommend\" is required"],
"skip": ["Skip is required"]
}
Implemented code:
fetch( 'https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
Try this way
import FormData from 'FormData';
...
var data = new FormData();
data.append("skip", "0");
data.append("module_type", "buy");
....
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
Sometimes when you work with REST API call you have to work with correct headers.
In your case I suppose your are missing two important headers required to activate a good communication between client and servers:
accept
content-type
Please review your code based on this one:
fetch('https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
I think the server is returning "missing" parameters because is not able to understand the type of content. With Content-Type you should be able to instruct the server on how to parse your data.
In postman is a section where you can put or set a header. But how do i set it but in the navigator, that lasts over time through requests to different routes?
I´ve already tried setting a header, from the backend with differents methods like, and none of both worked:
res.header('x-token', jwt)
Or like
res.set('x-token', jwt)
And from the frontend i already tried with this methods and it didn´t work either:
const data = {id_token};
//let myHeaders = new Headers();
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(resp => resp.json())
.then(({jwt}) => {
if (jwt) {
localStorage.setItem('x-token', jwt);
//None of both worked
//myHeaders.append('x-token', jwt);
//myHeaders.set('x-token', jwt);
}
})
.catch(error => console.error('Error:', error))
This is the header that i wanna send to the different routes:
https://i.stack.imgur.com/ueoxu.png
You can set the x-token header from your screen shot like this:
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json',
'x-token': 'eyJhbGciOiJIUzl.....'
}
}).then(...).catch(...)
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
i'm starting in react native and one thing i've been wondering is that, sometime i see fetch is used like this:
createTodo(){
fetch('http://192.168.1.34:3000/createTodo', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: this.state.noteText,
}),
}).then((response) => response.json())
.then((responseJson) => {
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': responseJson.data.content
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
console.log(responseJson);
}).catch((error) => {
console.error(error);
console.log('Shit! Error occured');
});
}
this work fine.
and sometime it is:
return fetch(...)...
I'm a bit confused.
fetch is Promise which returns another Promise. Resolved results passed to next .then input parameters. So in your example code, you can handle response values which is passed by fetch function.
You can return your fetch function when the client of createTodo wants to use the 'result' of createTodo. The 'result' is another Promise whose input parameters are from createTodo's return values
demo link: https://codesandbox.io/s/548lwxzyn
Demo is just for showing that return value of Promise is another Promise. I hope you can get hint.
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"