I am using ra-postgraphile as dataprovider for react-admin project and i need to intercept the error api response. Is there any error object or function available for that? if yes, Can I get a documentation.
Also posted an issue in ra-postgraphile repo.
Source Code
const httpLink = createHttpLink({
uri: Config.postgraphileUrl
});
const authLink = setContext((_, { headers }) => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
'Content-Type': 'application/json'
}
}));
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
useEffect(() => {
(async () => {
const dataProvider = await pgDataProvider(client);
setDataProvider(() => dataProvider);
})();
}, []);
Related
i am trying to set auth token in react native but it is not working.the api call to the url is woeking and data is saved to db but the token doesnot work
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(function (response) {
console.log('working');
ReactSession.setStoreType('Bearer', response.data.token);
ReactSession.set('username', 'Meon');
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
i get this error
console.log(response); returns the following
I use AsyncStorage together with fetch to set mine and then when i want to use it , I also call AsyncStorage from '#react-native-async-storage/async-storage';
After setting the state like this,
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
I try to simulate a Login
To login looks like this :
FunctionLogin = async () => {
let item = {email, password};
fetch('http://192.168.1.101/api/auth/sign-in', {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) => {
if (responseJson.message === 'OK') {
var token = responseJson.token;
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('token', token);
navigation.replace('Dashboard');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}
To use it in any page, I use it like this , later i reference the function in useEffect
showdata = async () => {
let token = await AsyncStorage.getItem('token');
alert(token);
};
Suppose I want to get transaction list from my endpoint to display data I do it like this
getTransactionsList = async () => {
let token = await AsyncStorage.getItem('token');
let email = await AsyncStorage.getItem('email');
var url = 'https://192.168.1.101/api/user-data/get-transactionby-email/';
fetch(url + email, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
};
Then suppose i want to call it inside useEffect, I do like this
useEffect(() => {
getTransactionsList();
});
Thats what and how i do it and it works fine. If you also know how to use Redux, its still a good one as well.
I have an Axios instance:
const axiosInstance = axios.create({
baseURL: API_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
axiosInstance.interceptors.request.use(async (config: any) => {
const accessToken = await getSecureValue('accessToken');
config.headers.Authorization = `Bearer ${accessToken}`;
return config;
});
And some API functions:
export const getProfile = async () => {
const response = await axiosInstance.get('/user/profile');
return response.data;
};
export const postContact = async (message: string) => {
await axiosInstance.post('/contact', { message });
};
A user can log in and it calls getProfile(), that all works.
But when I try the postContact:
const handleSendPress = async () => {
try {
await postContact(textInput);
} catch (error) {
console.log(error);
}
};
It comes back with an error from the server that the Authorization header is missing.
Adding a console.log() in the interceptor I can see that it is running before the request.
I'm running Android and iOS in emulators, and this only happens on iOS.
I'm very lost what this could be, since getProfile() works but postContact() doesn't and they both use the same Axios instance.
I'm working with api for movies, and to create a request to the server, I need to pass it to the header object
{
'X-API-KEY': 'there is apikey',
'Content-Type': 'application/json',
}
I make requests using RTK Query
export const filmsApi = createApi({
reducerPath: 'awaitsFilms',
baseQuery: fetchBaseQuery({
baseUrl: url,
}),
endpoints: (build) => ({
getAwaitsFilms: build.query({
query: () => `top?type=TOP_AWAIT_FILMS`,
}),
}),
})
how do I pass this header object to fetchBaseQuery?
Documentation
import type { RootState } from './store'
const baseQuery = fetchBaseQuery({
baseUrl: '/',
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token
// If we have a token set in state, let's assume that we should be passing it.
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
return headers
},
})
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 => {
//...
});
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));