fetch post always pass null to the parameters - react-native

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

Related

using data returned from promise in another fetch not working

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()
}

React Native: Not able to make post request for formData using axios or fetch

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,

415 coming back from requesting a token Spotify API

I'm trying to receive a token from Spotify api. Unfortunately I keep on receiving 415. Could you help me and let me know what am I doing wrong?
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
form: {
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.SPOTIFY_ID + ':' + process.env.SPOTIFY_SECRET).toString('base64')),
'Content-Type': 'application/json'
}
}).then(token => {
return token;
}).catch(e=> {
console.log(e);
return e.response;
});
};
module.exports = {
getToken
};
415 error code is related to problem with wrong content type or content encoding, (https://httpstatuses.com/415)
I do not know axios but please take a look on the example on spotify github https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L74
According to this issue on github (https://github.com/spotify/web-api/issues/321), try to use content-type 'Content-Type': 'application/x-www-form-urlencoded'
There is example withs axios
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "client_credentials"
},
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: "YOUR-CLIENT-ID",
password: "YOUR-CLIENT-SECRET"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
});
It works!!!
What I've done was:
- change Content-Type for 'application/x-www-form-urlencoded'
- client_id and client_secret were taken from header and posted before grant_type in body
- changed 'data' to 'params'
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
params: {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(token => {
return token;
}).catch(e=> {
return e.response.data;
});
};
And it resulted with a beautiful looking token \m/
After spending one hour trying to figure out how to get the token, I came up with this answer! :)
const axios = require('axios');
const express = require('express');
const app = express();
const client_id= 'YOURCLIENTID';
const client_secret = 'YOURCLIENTSECRET';
app.get('/api/token', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
grant_type: 'client_credentials'
},
json: true,
})
.then(body => {
res.send(body.data.access_token);
})
.catch(e => {
console.log(e.response.data);
});
});
app.listen(3000, () => {
console.log('Server Listening on port 3000');
});
If you making API call from client side (browser), try this solution:
getTokken() {
const urlSpotify = "https://accounts.spotify.com/api/token";
axios({
method: "post",
url: urlSpotify,
data: "grant_type=client_credentials",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.REACT_APP_SPTID_KEY, // User ID
password: process.env.REACT_APP_SPCS_KEY, // User Secret
},
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}

FacePlusPlus, "error_message": "MISSING_ARGUMENTS: api_key", with React Native fetch request

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

React Native - Fetch POST request is sending as GET request

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