Getting Network request failed when uploading images with apollo client react native android - react-native

I am using ApolloClient to send mutation that contains files (images) but I am getting
Error: Network request failed
this what I have done to create links
import { createUploadLink } from 'apollo-upload-client' v ==>> "^15.0.0";
const uploadLink = createUploadLink({
uri: API_URL,
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
"Accept":"application/json"
},
});
this to handle errors
import { onError } from "#apollo/client/link/error"; v ==>> "^3.3.20"
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network zaid error]: ${networkError}`);
});
then :
const client = new ApolloClient({
cache: new InMemoryCache(),
link: from([errorLink,uploadLink]),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'none'
},
mutate: {
mutation: "DocumentNode",
errorPolicy: 'none'
},
},
});
then I called the mutation :
await client.mutate({
mutation:
gql`
mutation($data: PostCreatInput!, $files: [CustomCreateImages!]!) {
createpost(data: $data, files: $files) {
id
}}`,
variables: {
data: {****},
files:[{file:ReactNativeFile}]
}
}).then(response => {
console.log(response);
return response
}).catch(response => {
console.log(response);
return response
})
i used ReactNativeFile generated by apollo-upload-client
new ReactNativeFile({
uri: "file:///storage/***.jpg",
name: "a.jpg",
type: "image/jpeg"
});
I am using react native "react-native": "0.62.2"
and I have a live server not using localhost
I did check the server logs this request never left the mobile; there was no record of it on the server.
been stuck all day on it, any help would be highly appreciated!

bug with React Native 0.62+ that messes up the configuration for multiform requests. It can be fixed by commenting out line 43 in android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java:
//builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

Related

react native laravel echo: can not find variable pusher

i have imported laravel-echo and #pusher/pusher-websocket-react-native in react native but error occur:can not find variable pusher
please tell me solution will be thankfully
import Echo from "laravel-echo";
import {
Pusher,
PusherMember,
PusherChannel,
PusherEvent,
} from '#pusher/pusher-websocket-react-native';
let echo = new Echo({
broadcaster: "pusher",
key: "123",
wsHost: "my-domain",
wsPort: 6001,
forceTLS: false,
cluster: "mt1",
disableStats: true,
authorizer: (channel, options) => {
console.log(options);
return {
authorize: async (socketId, callback) => {
console.log('socketId, callback',channel,socketId, callback)
const response = await fetch(`http://my-domain/api/broadcasting/auth`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
ContentType: 'application/json'
},
data: {
socket_id: socketId,
channel_name: channel.name,
},
})
.then((response) => {
console.log('fd',response);
callback(false, response.data);
})
.catch((error) => {
console.log('test',error)
callback(true, error);
});
},
};
},
});
=============================================================================================================================================
You must define Pusher to window
window.Pusher = Pusher;
Just write this line below the import

How to send axios reques in react native?

I'm new to React Native and I'm trying to send axios request to my backend but I'm stuck in it.
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
console.log('kk');
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(load_user());
};
when it tries to post request through axios it gives following error.
although I haved tried this in React JS and it's working perfectly.
please help me to solve this in react native
Per the React Native Networking Docs, React Native supports the fetch web API for sending requests. I advise you use fetch instead of axios as it has all of the same features without any added bloat and overhead. Here is a port of your code to use fetch:
export const login = (email, password) => async (dispatch) => {
const res = await fetch(`http://localhost:8000/auth/jwt/create/`, {
method: "POST", // this signnifies POST request type
body: JSON.stringify({ email, password }), // still including the body
headers: {
// apply the headers
"Content-Type": "application/json"
}
});
const data = await res.json(); // parses the body as a json object
console.log("kk");
dispatch({
type: LOGIN_SUCCESS,
payload: data
});
dispatch(load_user());
};
Try to use this way:
// define axios request
import axios from 'axios';
const request = axios.create({
baseURL: 'https://url.com/api/v1',
timeout: 20000,
});
request.interceptors.request.use(
config => {
// config.headers.Authorization = `Bearer ${token}`;
config.headers.Accept = 'Application/json';
return config;
},
error => {
//return Promise.reject(error);
console.log("interceptors.request: ", error);
return false;
},
);
request.interceptors.response.use(
response => {
if (response && response.data) {
return response.data;
}
return response;
},
error => {
console.log('Response error: ', error);
//throw error;
return false;
},
);
export default request;
Usage:
import request from '../';
export const getAPI = () => {
return request({
url: '/getData',
method: 'GET',
// ...
});
};
getAPI().then(response => {
//...
});

onError Import not being used in Apollo

I'm trying to handle errors on my React Native with Expo app, while using Apollo and Graphql.
The problem is that in my apolloServices.js I'm trying to use onError function, and despite I tried with both apollo-link-error and #apollo/client/link/error the import is still greyed out. The function it's at the ApolloClient.
React-native: 0.63.2
#Apollo-client: 3.3.11
Apollo-link-error: 1.1.13
// Apollo resources
import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from '#apollo/client'; // Tried putting onError here
import { onError } from 'apollo-link-error'; // And here
//import { onError } from '#apollo/client/link/error'; // Also here
import {
InMemoryCache,
defaultDataIdFromObject,
} from 'apollo-cache-inmemory';
import { setContext } from 'apollo-link-context';
/* Constants */
import { KEY_TOKEN } from '../constants/constants';
/**
* #name ApolloServices
* #description
* The Apollo Client's instance. App.js uses it to connect to graphql
* #constant httpLink HttpLink Object. The url to connect the graphql
* #constant defaultOPtions Object. Default options for connection
* #constant authLink
*/
const httpLink = new HttpLink({
uri: 'workingUri.com',
});
const defaultOptions = {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
};
//Create link with auth header
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
return AsyncStorage?.getItem(KEY_TOKEN).then((token) => {
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
'auth-token': token ? token : '',
},
};
});
});
export default new ApolloClient({
/* ON ERROR FUNCTION HERE*/
onError: (graphQLErrors, networkError) => {
if (graphQLErrors)
graphQLErrors.map(
({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
},
cache: new InMemoryCache(),
defaultOptions: defaultOptions,
link: authLink.concat(httpLink),
request: (operation) => {
operation.setContext({
headers: {
'auth-token': token ? token : '',
},
});
},
});
Appart from this, the app is working perfectly, what I want it's just to handle graphql and network errors
The best solution would be to use this approach
const errorControl = onError(({ networkError, graphQLErrors }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.log(
" [GraphQL error]: Message", message, ", Location: ", locations, ", Path: ", path)
);
}
if (networkError) {
console.log(" [Network error]:", networkError)
};
});
export default new ApolloClient({
cache: new InMemoryCache(),
defaultOptions: defaultOptions,
link: errorControl.concat(authLink.concat(httpLink)),
headers: {
authorization: token ? token : '',
},
});

Fail to connect to GraphQL API server

I'm running an online GraphQL API, it seems to work fine when I'm trying postman for example to make requests, but always fails, with Apollo Link React-native, that returns error: TypeError: Network request failed.
const cache = new InMemoryCache();
const token = this.props.account.accessToken || "";
const httpLink = createHttpLink({
uri: config.graphql_host,
credentials: "same-origin",
});
const websocket = new WebSocketLink({
uri: `ws://${config.ws_host}`,
options: {
reconnect: true,
connectionParams: { authorization: `Bearer ${token}` },
},
});
const middleware = new ApolloLink((operation, forward) => {
operation.setContext({ headers: { authorization: `Bearer ${token}` } });
return forward(operation);
});
const splitlink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
websocket,
httpLink
);
const client = new ApolloClient({
connectToDevTools: true,
link: concat(middleware, splitlink),
cache: cache,
defaultOptions: {
watchQuery: { fetchPolicy: "cache-and-network", errorPolicy: "all" },
query: { fetchPolicy: "cache-and-network", errorPolicy: "all" },
},
mutate: { errorPolicy: "all" },
});
package.json:
"#apollo/client": "^3.1.3",
"#apollo/react-hooks": "^3.1.5",
"apollo-link-http": "^1.5.17",
"apollo-cache-inmemory": "^1.6.6",
I get the error as follow:
Error: Network error: Network request failed
at new ApolloError (bundle.umd.js:92)
at Object.error (bundle.umd.js:1330)
at notifySubscription (Observable.js:140)
at onNotify (Observable.js:179)
at SubscriptionObserver.error (Observable.js:240)
at bundle.umd.js:1107
at Set.forEach (<anonymous>)
at Object.error (bundle.umd.js:1106)
at notifySubscription (Observable.js:140)
at onNotify (Observable.js:179)
I found the solution, the SSL installed on the server was invalid so I had to use Free Let's Encrypt SSL and worked perfectly. In fact the request was reject constantly.

How to upload image to server in React Native

I'm trying to upload image by using React Native axios. But I get this response. I tried every solutions but it didn't work. I'm using react-native-image-picker to get image
{ result: null,
message: 'Wrong access',
error: true,
type: 'command_not_found' }
Here is my code
ImagePicker.showImagePicker(options, (response) => {
let formData = new FormData();
formData.append('image', { uri: response.uri, name: response.fileName, type:response.type });
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios({
url: "URL",
method: 'POST',
data: formData,
config
})
.then(result => console.log(result))
.catch(error => console.log(error))
}
Try with raw fetch api.
const createFormData = (photo) => {
const data = new FormData();
data.append("photo", {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
});
return data;
};
and then try to upload it again
fetch("http://localhost:3000/api/upload", {
method: "POST",
body: createFormData(photo)
});