React js Axios call - reactjs

I'm fairly to new to React and I can't seem to be able to successfully make a call to an external API using Axios.
The guidelines of the external API are:
Request (in case we know all the parameters)
{
"service": "login",
"username": "john",
"password":"aitis",
"appId": "2001",
"COMPANY": "1000",
"BRANCH": "1000",
"MODULE": "0",
"REFID": "1",
---- optional ---
"LOGINDATE": "2017-12-31 13:59:59",
"TIMEZONEOFFSET": -120
}
Response
{
"success": true,
"clientID": "Wj8Te8EqWghDM......... .....wYGtzlyc1At%2bPrG8t"
}
My code is:
componentDidMount() {
axios.get('http://...serverurl....', {
params: {
service: 'login',
username: 'john',
password: 'aitis',
appID: '2001',
company: '1000',
branch: '1000',
module: '0',
refid: '1'
},
headers: {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
}
})
.then(response => console.log(response));
}
Instead of getting the clientID response I get this:
Response
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
data:
success: false
errorcode: 0
error: "JSON Object must begin with "{" at character 2 of service=login&username=john&password=aitis&appID=2001&Company=1000&Branch=1000&Module=0&Refid=1 JSON Syntax Error : at charact↵
error on character : 2"
__proto__: Object
status: 200
statusText: ""
...
Is something wrong with my call?
Thanks in advance.

If want to send a GET request with those params set those in URL
const URL = `${baseURL}/url?service=login&username=jhon&password=aitis&appID=2001&company=1000&branch=1000&module=0&refid=1`;
axios.get(URL).then(response => console.log(response));

I figured it out. I had to use axios.post instead of axios.get.
Thank you all very much

Related

Local HTTP Request not sending with Axios on React Native Expo app

I am writing a react native expo app that utilizes a .NET backend that I've already established and has worked quite well for a while. Recently, I've gotten to the point of attempting local http requests with axios for my mobile app rather than mock data, and it worked wonderfully for a bit. I have a few get requests that are called in a useEffect like this:
useEffect(() => {
async function getAll() {
const response = await axios({
method: 'GET',
url: `${baseUrl}/ItemName`,
headers: {
authorization: `Bearer ${authToken}`,
'content-type': 'application/x-www-form-urlencoded'
}
}).catch(err => console.log(err));
if(response?.data) {
setItemName(response.data);
}
}
getAll();
}, []);
Then after that was working, I wanted to put in authentication within the app itself rather than using the backend Swagger and copying the token every 30 minutes. Made a signup page and the form worked just fine, but when I made the new axios post request, none of the requests worked - even those that were working before hand. The post looks like this:
const postNewUser = async (values) => {
try {
const postObject = {
method: 'POST',
url: `${baseUrl}/User/Register`,
data: {
firstName: values.firstName,
lastName: values.lastName,
username: values.username,
password: values.password,
email: values.email,
phoneNumber: values.phone,
birthDate: moment(values.birthDate).toISOString()
},
headers: {
'content-type': 'application/json'
}
};
const response = await axios(postObject);
if(response) {
navigation.navigate('Login', {
desiredUsername: values.username
});
}
} catch(err) {
console.log('Error: ', err);
}
}
I've been googling for over a week now trying different answers multiple different times. I've tried updating my nodejs, tried different versions of axios, tried different baseUrls for the request (localhost, 10.0.2.2, and my personal IP) but none of them work. Strangely, localhost and my IP both return very quickly, and 10.0.2.2 takes a solid 30 seconds but returns the same error message.
I have put a log into the user controller on my backend to show whether or not I'm actually hitting the backend or not, and with postman or swagger I get there just fine. With the mobile axios call I don't hit that log, so I'm not even getting to the backend at all. Instead I'm getting a not-so-useful error as follows:
Stack: AxiosError#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:114554:29
handleTimeout#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:115572:39
dispatchEvent#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:30065:31
setReadyState#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:28693:33
__didCompleteResponse#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:28499:29
emit#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:2310:40
__callFunction#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21321:36
#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21071:31
__guard#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21269:15
callFunctionReturnFlushedQueue#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21070:21
callFunctionReturnFlushedQueue#[native code]
Message: timeout exceeded
Name: AxiosError
Code: ECONNABORTED
Config: {
"adapter": [
"xhr",
"http"
],
"data": "{\"firstName\":\"Test\",\"lastName\":\"Test\",\"username\":\"test\",\"password\":\"P#ssw0rd\",\"email\":\"email#example.com\",\"phoneNumber\":\"5555555555\",\"birthDate\":\"2022-11-27T19:13:57.458Z\"}",
"env": {
"Blob": [Function Blob
],
"FormData": [Function FormData
]
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"maxBodyLength": -1,
"maxContentLength": -1,
"method": "post",
"timeout": 0,
"transformRequest": [
[Function transformRequest
]
],
"transformResponse": [
[Function transformResponse
]
],
"transitional": {
"clarifyTimeoutError": false,
"forcedJSONParsing": true,
"silentJSONParsing": true
},
"url": "http://10.0.2.2:5000/api/User/Register",
"validateStatus": [Function validateStatus
],
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN"
}
Request: {
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": true,
"_headers": {
"accept": "application/json, text/plain, */*",
"content-type": "application/json"
},
"_incrementalEvents": false,
"_lowerCaseResponseHeaders": {},
"_method": "POST",
"_perfKey": "network_XMLHttpRequest_http://10.0.2.2:5000/api/User/Register",
"_performanceLogger": {
"_closed": false,
"_extras": {},
"_pointExtras": {},
"_points": {
"initializeCore_end": 606677771.370125,
"initializeCore_start": 606677745.343875
},
"_timespans": {
"network_XMLHttpRequest_http://10.0.2.2:5000/api/User/Register": [Object
],
"network_XMLHttpRequest_http://personalIp:19000/logs": [Object
],
"network_XMLHttpRequest_http://personalIp:19000/symbolicate": [Object
],
"network_XMLHttpRequest_http://personalIp:5000/api/User/Register": [Object
],
"network_XMLHttpRequest_http://localhost:5000/api/User/Register": [Object
]
}
},
"_requestId": null,
"_response": "The request timed out.",
"_responseType": "",
"_sent": true,
"_subscriptions": [],
"_timedOut": true,
"_trackingName": "unknown",
"_url": "http://10.0.2.2:5000/api/User/Register",
"readyState": 4,
"responseHeaders": undefined,
"status": 0,
"timeout": 0,
"upload": {},
"withCredentials": true
}
I'm testing this currently on my mobile expo app. I've tested in the past on the web version but SecureStore doesn't work with web. I was able to confirm before adding the new requests that the mobile version was able to call the getAll just fine before the signup was added.

How to pass body in post request fetch api call in React Native

My url if opened on browser gives the following error:(attached image)
Body of my api call looks like below :
{
"entityId": 4071,
"listViewId": 0,
"asLookup": false,
"retrieveAllFields": true,
"fullTextSearch": "",
"query": [
],
"pagination": {
"pageNumber": 0,
"recordsCountPerPage": 0
},
"sorting": {
"fieldId": 0,
"direction": 0
}
}
I am calling api in react native using fetch below :
try {
let response = await fetch('url', {
method: 'POST',
headers: {
'tenantid': '1',
'Content-Type': 'application/json',
'language': '0',
},
body: JSON.stringify({
entityId: 4071,
listViewId: 0,
asLookup: false,
retrieveAllFields: true,
fullTextSearch: "",
query: [
],
pagination: {
pageNumber: 0,
recordsCountPerPage: 0
},
sorting: {
fieldId: 0,
direction: 0
}
})
})
let json = await response.json();
console.log("This is response" + json)
this.setState({records: json.results, isFetching:false});
}catch(error){
this.setState({errorMessage:error})
console.log("This is error"+error)
}
This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!
did you use the correct url ?
it should looks like something like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
maybe you should look on the documentations
https://reactnative.dev/docs/network

Unable to resolve POST call on redux observable

I am working on a react native application and on having a POST call with Observable.fromPromise, I am getting the below response, but I am not sure how to capture the response in terms of code and I amgetting some warnings as well
Response :
PromiseObservable {_isScalar: false, promise: Promise, scheduler: undefined}
promise: Promise
_40: 0
_55: Promise
_40: 0
_55: Promise
_40: 0
_51: 3
_55: Response
bodyUsed: true
headers: Headers {map: {…}}
ok: true
status: 200
statusText: undefined
type: "default"
url: "http://localhost:9999/testPath/pathData"
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}
__proto__: Object
_65: 2
_72: null
__proto__: Object
_65: 3
_72: null
__proto__: Object
_65: 3
_72: null
__proto__: Object
scheduler: undefined
_isScalar: false
__proto__: Observable
Warning :
YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "D985543E-CD51-470C-91F9-3407AE59FDA1",
"name": "test-data",
"offset": 0,
"size": 0,
"type": "application/json",
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "D985543E-CD51-470C-91F9-3407AE59FDA1",
"name": "test-data",
"offset": 0,
"size": 0,
"type": "application/json",
},
},
"bodyUsed": true,
"headers": Headers {
"map": Object {
"content-type": "application/json; charset=UTF-8",
"server": "Jetty(9.2.z-SNAPSHOT)",
"transfer-encoding": "Identity",
},
},
"ok": true,
"status": 200,
"statusText": undefined,
"type": "default",
"url": "http://localhost:9999/testPath/pathData",
}
I am using mergeMap to capture the response, not sure why is it not working in this case
Code:
const testEpic: Epic<Action, ReduxState> = (
action$: ActionsObservable<any>,
store: MiddlewareAPI<any, ReduxState>,
) =>
action$
.ofType(TEST_GET)
.mergeMap((action) => {
return Observable.merge(
.fetch('/testPath/pathData', payload) // return part which is working properly
.mergeMap((response) => {
// calls not coming here for POST, PUT, DELETE even though it is status 200
})
)
}
)
.catch((error) => {
})
Try this
fetch("/testPath/pathData", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I have resolved it,actually it was going inside 'error' because of mismatch of contentType

How to display image returned from fetch() method - react-native

I have the following code to retrieve an image from an API
await fetch('https://example.com/api/user/fileaccess', {
method: 'POST',
headers: {
Accept: '*',
'Content-Type': 'application/json',
'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
},
body: JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
}).then((response) => {
console.log(response);
});
The request was completed and i got log in my console.
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId":
"xxxxx-xxxx-xxx-xxxx-xxxxx", "offset": 0, "size": 953328}},
"_bodyInit": {"_data": {"__collector": [Object], "blobId":
"xxxxx-xxxx-xxxx-xxxx-xxxxx", "offset": 0, "size": 953328}},
"headers": {"map": {"cache-control": "max-age=2592000", "connection":
"Keep-Alive", "content-type": "image/jpeg", "date": "Tue, 04 Feb 2020
10:34:14 GMT", "expires": "Thu, 05 Mar 2020 10:34:14 GMT",
"keep-alive": "timeout=5, max=100", "pragma": "public", "server":
"Apache", "transfer-encoding": "chunked"}}, "ok": true, "status": 200,
"statusText": undefined, "type": "default", "url":
"https://example.com/api/user/fileaccess"}
My question is, How to display this data as an image in my app? Is it possible to convert a base64 from this data?
You need to extract it into json or text or some other data before you can do anything with the response.
As per Mozilla docs, A basic fetch request is really simple to set up. Have a look at the following code:
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
So, modify your code as below :
fetch('https://example.com/api/user/fileaccess', {
method: 'POST',
headers: {
Accept: '*',
'Content-Type': 'application/json',
'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
},
body: JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
})
.then(response => response.json())
.then((result) => {
console.log("Your intended result is: " , result)
});
The response.json() is added just assuming the server is returning a JSON data.
If not, you can try the below methods too based on your server implementation.
arrayBuffer()
blob()
json()
text()
formData()
If that's the image URL you can go ahead as follows
Store image in your state
this.setState({image:res.url})
and then <Image source={{uri:this.state.image}}/>

how can I retrieve data from my backend in a table with reactjs?

I want to retrieve all usernames from my django backend using axios. The users where shown in a console, but all the details data:(username email...) ,headers, token ....
So I want to restrict that to just get the data or just show the data in the console
After that I want to know how can i put the usernames in a table or a list
This is my retrieve function :
const RetrievUsers=()=>{
axios.get('http://127.0.0.1:8000/user/list')
.then(data =>
console.log(data)
)
.catch(err=>console.log(err))
}
The data in my back-end looks like this:
"username": "pol",
"password": "**********************",
"nom": "a",
"prenom": "a",
"email": "a#gmail.com",
"residence": "po",
"phone": "po"
console :
{data: Array(2), status: code, statusText: " ", headers: {…}, config: {…}, …}config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, ###}
/I need only this part
data:Array(2)
0: email: "a#gmail.com"nom:"a "password: "***pbkd g=" phone: "po"
prenom: "a"residence: "po"username: "pol"__proto__: Object
1: email: "a#gmail.com" nom: "a" password: "*****A4=" phone: "a"
prenom: "a"residence: "pass"username: "a"__proto__: Object
//
length: 2__proto__: Array(0)headers: { }request: XMLHttpRequest {onreadystatechange:  …}status:
for filtering the username just try consoling like this
console.log(data.data[0].username);
for looping through the data try this
data.data.forEach(function(element) {
console.log(element.username);
});

Resources