I'm having issues when using FETCH.
I am trying to make a POST request using FETCH in react-native.
fetch("http://www.example.co.uk/login", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'test',
password: 'test123',
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
})
.done();
}
When I inspect this call using Charles it is recorded as a GET request and the username and password that should be in the body are not there.
Can anyone help with this issue?
I had this issue when the POST request was to an HTTPS (rather than HTTP) server. For some reason, it would somewhere along the way be converted into a GET request.
It turns out what I was doing incorrectly was sending the request to http://myserver.com:80 rather than to https://myserver.com:443. Once I switched it over to the proper prefix and ports, the request would properly send as a POST.
This worked for me:
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
appoid: appo_id
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.load('csrftoken')
}
}
return fetch('/appointments/get_appos', data)
.then(response => response.json()) // promise
.then(json => dispatch(receiveAppos(json)))
}
Use FormData. Problem is with JSON.stringify. You can directly import, its not third party
import FormData from 'FormData';
...
var data = new FormData();
data.append("username", "ABCD");
data.append("password", "1234");
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);
});
I had the same kind of issue. You have to assign the object, not sure why.
let options = {};
options.body = formdata;
options.header = header;
options.method = 'post';
In my case, the redirect was caused by wrongly formed url for the POST request:
http://localhost:90/Worx/drupal/d8/www//jsonapi
double slash before jsonapi
Because of the wrong url, the browser was redirecting the request and changing the method from POST to GET.
I was able to debug it after reading this:
https://serverfault.com/questions/434205/nginx-https-rewrite-turns-post-to-get
If you wanna do POST request using fetch, You can do like that
fetch('url?email=a#gmail.com&password=a#gmail.com', {
method: 'POST'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
// this.setState({
// data: responseJson
// })
})
.catch((error) => {
console.error(error);
});
Redirection of url converts the POST request into GET requests.(Don't know why)
So make sure of adding trailing arrows if any.
like :"http://www.example.co.uk/login/"
I had the same issue. In my case I had an extra / at the end of my route. I removed it and problem solved.
http://google.com/someData/ to http://google.com/someData
I have made some changes and tested it, works fine for me, check below all the changes:
constructor(props) {
super(props);
this.state = { isLoading: true};
this.getRemoteData();
}
getRemoteData = () => {
fetch('http://www.example.co.uk/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'test',
password: 'test123',
})
})
.then((response) => response.json())
.then((responseData) => {
console.log("RESULTS HERE:", responseData)
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
})
};
Check your OPTIONS response. It probably has a 302 redirect or similar.
In our case, Django didn't like it if the URL didn't end in a /
Similar to Rishijay's answer, my issue was with JSON.stringify not properly converting the body of POST request.
The way I solved this was using build from the search-params node module to make it work.
My fetch contents had body like this body: build({...})
This worked for me!
const params = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: '1',
name: 'user',
age: '26',
}),
};
fetch('https://yourapi/', params)
.then(response => response.json())
.then(data => console.log(data));
Related
I have a handleSubmit function that I have added two post requests to.
However, one of the post requests relies on the data returned from the first post request. I've attempted to access this data by setting it to a var but it doesn't seem accessible within the second fetch. Not sure if my syntax is wrong.. any ideas?
I believe this should be working but I'm not sure where I'm going wrong. Thanks!
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
var dataId = data.id;
})
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: dataId,
user_id: this.props.users.id
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
There's 2 problems:
You return some code and then try to run something else. Your this.props.navigation.goBack() statement will never be reached because the function ends when it reaches the return. That is not your main problem though.
fetch is asynchronous. It means that the function handleSubmit will read the two first statements ("fetch resources" and "return fetch user_resources") and then when each fetch is finished they will run their .then() functions.
This means your dataId will be undefined and you need to wait for the first fetch to complete and to execute the 2nd fetch.
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: data.id,
user_id: this.props.users.id
})
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,
I'm fairly new to react native and I'm trying to test out using the FacePlusPlus API (https://console.faceplusplus.com/documents/5679127).
Here, I've tried putting 'api_key' in the body, however, I've also tried putting it in headers too. Neither has worked.
componentDidMount() {
var url = 'https://api-us.faceplusplus.com/facepp/v3/detect';
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_key: 'blahblahblah',
api_secret: 'blahblahblah',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
In render(), I put console.log(this.state.data) where data is an array to see the response, however all I keep getting is
Object {
"error_message": "MISSING_ARGUMENTS: api_key",
}
To solve this problem you have to set Content-Type header to 'application/x-www-form-urlencoded'
and pass your arguments as formData.
I put the example with using 'request' npm package.
const request = require('request');
request.post({url:'https://api-us.faceplusplus.com/facepp/v3/compare', formData: {
api_key: 'your api key',
api_secret: 'your api secret',
image_url1: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/George_Lucas_cropped_2009.jpg/220px-George_Lucas_cropped_2009.jpg',
image_url2: 'https://imgix.bustle.com/uploads/getty/2018/6/13/e4c5921d-3e23-4f13-87fe-0180005d0ace-getty-929360234.jpg?w=970&h=582&fit=crop&crop=faces&auto=format&q=70'
}}, (err, httpResponse, body) => {
if (err) {
return console.error('error', err);
}
console.log('success ', JSON.parse(body));
});
There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?
fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userid: '404',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
//return responseJson.message;
this.setState({
data: responseJson.message
})
})
.catch((error) => {
console.error(error);
});
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.
const method = async () => {
const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
userid: "404"
})
});
const responseJson = await response.json();
this.setState({ data: responseJson.message });
};
Im trying to handle a "Network request failed" error (I already allowed unsecured connections from Xcode), But when i try to do something inside the .error() function it crashes and says: .error is not a function; The fetch() works already.
here's an example of it, Im trying to run this code after a fetch function.
fetch('URL',{
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data}
)
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.error((error)=>{
console.error(error);
Actions.login()
});
React's fetch method returns a Promise, which doesnot have .error() method. Instead it has .catch() method to catch all errors when fetch fails.
fetch('URL', {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data
})
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.catch((error) => {
console.error(error);
Actions.login()
});