Issue using Relay mutations with files - react-native

I have an issue using File Mutation with Relay. I am trying to create a mutation using getFiles()
Relay.Store.commitUpdate(
new AddOrderMutation({userId: userId, medications: OrderInputTypeMedication,
userAddressId:userAddressId,files:files}),
{
onSuccess: (response) => OnResponseSuccess(response),
onFailure: (transaction,e) => console.log('transaction',transaction.getError(),'e',e),
},
);
}
I always get an error that said
transaction TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (D:\ReactNative\MedexApp\node_modules\react-native\node_modules\whatwg-fetch\fetch.js:436)
although all other requests are working good. also the same mutation is sent correctly without attaching any files.
this is the array of files ["1489322712989.jpg":{filename:"1489322712989.jpg"
uri:"file:///storage/emulated/0/Pictures/1489322712989.jpg"}]
and It never sends the request through fiddler or caught in the webservice

I wasn't adding to the Files Object (type: 'image/jpg'), so the file Object should be as follows:
file ={
uri: this.state.image.uri,
name: this.state.image.name,
type:'image/jpg'
};

Related

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

Handling errors if no network is available

I just implemented my first backend file where I fetch some user data, messages and so on.
Now I wanted to include error handling if there is no network available.
I don´t know if I did it right but this was my approach so far:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
In my mounted() function of my main view I fetch the data from my backend file from above:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
I tried to check in console if it is working but all I get is the following:
In the catch block I check for
response errors: like 4xx/5xx
request errors: if my network not responding in time
and any other errors
Would this be the right approach to check if a network is available or not? Or does it degrade the user experience when the user checks the error?
My backend file includes more methods.. do I have to write for each method these kind of requests?
In your backend file you don't react whether there is a network connection or not I think.
And only for reference: that is not the backend, but communicates with the backend - the backend is the part of your code what you communicate with, e.g. Laravel code, an API, ...
Try adding the following at the beginning of your catch part:
if (!error.response) {
//network error
console.log('No network connection');
} else if (error.response) {
//the rest of your code
This should print out No network connection in your console.
Run your application, turn off the internet connection and check the console.
These kind of code should always be located in your backend part.
My answer maybe different from your question.
When i create a .net core API with Angular i used three things to check is there network or not?
subscribe to windows's offline/online event
create signalR hub from layout component to API server
API request failed (it means lot of incident, but if 1. or 2. case is true i know what cause 3. case

Error when creating a wallet using kin.js

Trying to embed kin.js in an Ionic App, I can see that the key creation using Keypairs and network initialization is ok
const keys = Keypair.random();
const network = KinNetwork.Production;
However when I try to create the wallet
createWallet(network, keys)
.then(res => {
console.log(res);
}, (err) => {
console.log(err)
});
It keeps retrying but at the end it replies with Error: failed to load account:
I can see the API call is made
https://horizon-kin-ecosystem.kininfrastructure.com/accounts/GANWXV7IHG6YGWVIXJNB56OCBIYI7LYKD34CH556YCDOP5LRC2WDJLTC?c=0.32263221858689695
but the response includes this object
{
“type”: “https://stellar.org/horizon-errors/not_found",
“title”: “Resource Missing”,
“status”: 404,
“detail”: “The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our database could be found with the parameters provided.”
}
Any missing parameters I should supply beyond the network and keys

Network error with axios and react native

I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)
This is my axios call in my react native component:
componentDidMount() {
axios.get('mydomain.com/get/').then(response => { // localhost:8000/get works
this.setState({foo:response.data});
}).catch(error => {
console.log(error);
});
}
If you are trying to call localhost on android simulator created with AVD, replacing localhost with 10.0.2.2 solved the issue for me.
It seems that unencrypted network requests are blocked by default in iOS, i.e. https will work, http will not.
From the docs:
By default, iOS will block any request that's not encrypted using SSL.
If you need to fetch from a cleartext URL (one that begins with http)
you will first need to add an App Transport Security exception.
change from localhost to your ip(192.168.43.49)
add http://
http://192.168.43.49:3000/user/
If you do not find your answer in other posts
In my case, I use Rails for the backend and I tried to make requests to http://localhost:3000 using Axios but every time I got Network Error as a response. Then I found out that I need to make a request to http://10.0.2.2:3000 in the case of the android simulator. For the iOS simulator, it works fine with http://localhost:3000.
Conclusion
use
http://10.0.2.2:3000
instead of
http://localhost:3000
update
might worth trying
adb reverse tcp:3000 tcp:3000
For me, the issue was because my Remote URL was incorrect.
If you have the URL is a .env file, please crosscheck the naming and also ensure
that it's prefixed with REACT_APP_ as react might not be able to find it if named otherwise.
In the .env file Something like REACT_APP_BACKEND_API_URL=https://appurl/api
can be accessed as const { REACT_APP_BACKEND_API_URL } = process.env;
Try
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
If you are using android then open your command prompt and type ipconfig. Then get your ip address and replce it with localhost.
In my case, first I used http://localhost:8080/api/admin/1. Then I changed it to http://192.168.1.10:8080/api/admin/1. It worked for me.
Make sure to change localhost to your_ip_address which you can find by typing ipconfig in Command Prompt
Trying adding to your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I was facing the same issue.
i looked deeper and my
endpoint url was not correct.
By giving axios right exact url, my api worked like charm.
Hope it may help anyone
Above mentioned answers only works if you are using localhost but if your code is hosted on a server and Axios throwing Network Error then you can solve this by adding one line.
const config = {
method: 'post',
url: `${BASE_URL}/login`,
headers: {
'Content-Type': 'multipart/form-data'. <----- Add this line in your axios header
},
data : formData
};
axios(config).then((res)=> console.log(res))
I'm using apisauce dependancy & Adding header work for me with React Native Android.
Attach header with request like below:
import { create } from 'apisauce';
const api = create({
baseURL: {baseUrl},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
export async function empLogin(data) {
try {
const response = api.post('Login', data);
return await response;
} catch (error) {
console.log(error);
return [];
}
}
before:
axios.get("http://localhost:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
I get Error "Network error" Failed to connect to the localhost after that, I make some steps to resolved the error.
Network Error related to axios resloved by the disabling the system firewall and access from the system IP Address like
axios.get("http://192.168.12.10:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
For me adding "Accept" in headers resolved the problem:
Accept: 'application/json'

make a HTTP Request from React-Redux from localhost

I am new to React Redux, and All I already did:
1) activate my backend server (localhost:5000)
2) activate my front-end server using npm start (localhost:8080)
3) I tried to dispatch action by using
this.props.dispatch({type: ActionTypes.FILE_UPLOAD_REQUEST, email: this.state.email, file: this.state.policyFile});
4) Using atlas-saga, and call my service function associated with the dispatch :
let result = yield call(Atlas.uploadFile, action.email, action.file);
5) define the function as :
export const uploadFile = (email, file) => {
return fetch(`${BASE_URL}/v1/files/${email}/policies`, {
method: 'POST',
headers:{} ,
body: {'file': file}
})
.then(response => response.json())
}
After I try to run a function at my react( a function that calls the dispatch), it gives me errors that they cannot found the route. This is the error message from the console.
Fetch API cannot load https://api-staging.autoarmour.co/v1/files/fakeemail#gmail.com/policies. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Yes, I did not create any reducer, just pure function that will upload a file. Thank you
I SOLVE IT, WOHOO!!!
The error message means that its not connected at the backend side at all. You need to make sure that it is connected. I solve it by connecting my redux to my react component. Thanks guys
Cheers!