I use this code to fetch a token successfully if I run it from node. However, it fails, and I notice the body received in the server end is empty when I run it in React Native. What is wrong in React Native?
function fetchToken() {
console.log("fetchToken");
const fetch = require("node-fetch");
const params = new URLSearchParams();
params.append('client_id', '1234567');
params.append('client_secret', 'abcdefg');
const url = "https://example.com/token";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(url, {method: 'POST', headers: headers, body: params})
.then(response => response.json())
.then((resp) => {
console.log(resp);
})
.catch(error => console.error('Unable to fetch token.', error));
console.log("fetchToken done");
}
Related
I can fetch contents from my Django server with which code below.
But i need fetch from also another URL : http://127.0.0.1:8000/userpost/tagpool/
I don't know how to do. Please help.
useEffect(() => {
fetch("http://127.0.0.1:8000/api/contents/", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token xxxxxxxxxxxxxx'
}
})
.then( resp => resp.json())
.then( resp => setFeatured(resp))
.catch( error => console.log(error))
}, [])
Use Promises chaining or Chaining
For example,
// Make a request for user.json
fetch('http://localhost/article/promise-chaining/user.json')
// Load it as json
.then(response => response.json())
// Make a request to GitHub
.then(user => fetch(`https://api.github.com/users/${user.name}`))
// Load the response as json
.then(response => response.json());
My issue is:
I need to get some data from an API using axios library, but for some cases, it is just not working.
This is a working example:
const RAPIDAPI_API_URL = 'https://cbsservis.tkgm.gov.tr/megsiswebapi.v3/api/parsel/40.89253647288918/29.236472547054294/';
const RAPIDAPI_REQUEST_HEADERS = {
'Content-Type': 'application/json'
};
axios.get(RAPIDAPI_API_URL,{ headers: RAPIDAPI_REQUEST_HEADERS })
.then(response => {
const data = response;
console.log(data);
})
.catch(error => console.error('On create error', error));
But when the value of RAPIDAPI_API_URL is changed to "http://jsonplaceholder.typicode.com/users", it throws the following error:
Network Error
at e.exports (https://unpkg.com/axios#0.19.2/dist/axios.min.js:2:9633)
at XMLHttpRequest.l.onerror (https://unpkg.com/axios#0.19.2/dist/axios.min.js:2:8398)
You have to load the request over https not http. Find sample here
const RAPIDAPI_API_URL = 'https://jsonplaceholder.typicode.com/users';
const RAPIDAPI_REQUEST_HEADERS = {
'Content-Type': 'application/json'
};
axios.get(RAPIDAPI_API_URL,{ headers: RAPIDAPI_REQUEST_HEADERS })
.then(response => {
const data = response;
console.log(data);
})
.catch(error => console.error('On create error', error));
I've got an API where some of the parameters need to be given within the URL.
Example of how my api url looks like: https://www.server.com/api/actions/execute?auth_type=apikey&data={"Name": "name","Email" : "email"}
What my code looks like right now
register = async () => {
let data = {"Name":this.state.name, "Email":this.state.email}
data = JSON.stringify(data)
let URL = 'https://www.server.com/api/actions/execute?auth_type=apikey&data=';
fetch(URL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: data
})
.then((response) => response.text())
.then((responseText) => {
alert(responseText);
})
.catch((error) => {
console.error(error);
});
}
The response I get on my device:
{"code":"succes","details":{"userMessage":["java.lang.Object#2e56000c"],"output_type":void","id:"20620000000018001"},"message":"function executed succesfully"}
This is alle working fine when I test it in postman but I can't get it to work within React-Native. I've tried stuff like 'Content-Type':'application/x-www-form-urlencoded' already.
First install the package axios from the url https://www.npmjs.com/package/react-native-axios
Then create two service for handling get and post request so that you can reuse them
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
PostService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const PostService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.post(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
Sample code for using get and post services is given below
import { PostService } from './PostService';
import { GetService } from './GetService';
let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });
let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
If you need to pass parameters via URL you should use GET, if you use POST then the parameters should be passed in the body
i am fetching some data by using POST api call in which i have data and a token value for header, but i am getting bad response and i checked many docs but can't figure out the error, here is the code:
export const shareUserProfileHandler = (sharedReceiverData) => {
return dispatch => {
let formData = new FormData();
for (let key in sharedReceiverData) {
formData.append(key, sharedReceiverData[key]);
}
let requestConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Token 97a74c03004e7d6b0658b14ddb'
},
body: formData
};
fetch(`http://api.com`, requestConfig)
.then(response => response.json())
.then(response => {
alert('share user card api worked')
})
.catch(error => {
alert('api error ' + error)
})
}
};
the above is catching error and showing - SyntaxError: JSON Parse error: Unrecognized token'<'
Your response doesn't seem to be a JSON.
Replace
.then((response) => response.json())
For
.then((response) => { console.log('response', response); response.json() })
And check what is wrong with the response before the error.
I am trying to fetch data from a Socrata API and then post it to my own database. When I run the function in node, I get the error "ReferenceError: fetch is not defined"
I am totally lost, and am wondering how to pull this off. I have been googling for the past four hours, and can't find anything.
My code:
const apiURL = "https://ftbserver.herokuapp.com/npos"
const soda = require('soda-js');
var consumer = new soda.Consumer('data.colorado.gov');
let stuff
consumer.query()
.withDataset('p3jp-z4tq')
.limit(2)
.where({ principalcity: 'Denver' })
// .order('namelast')
.getRows()
.on('success', function (rows) {
rows.map((nposNew) => {
let data = {
fein: nposNew.fein,
name: nposNew.name,
revenuetotal: nposNew.revenuetotal,
expensestotal: nposNew.expensestotal
}
fetch(apiURL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
})
.then(response => response.json())
.then(response => {
showSuccess(response.message)
setTimeout(() => (removeMsg()), 4000);
})
.catch(console.error);
})
})
.on('error', function (error) { console.error(error); });
// console.log(stuff);
// console.log(npost);