How to send axios reques in react native? - 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 => {
//...
});

Related

Axios interceptors not adding headers on some requests in React Native, iOS only

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.

How do I make this axios call inside my own API route?

This is my first time trying to make an API call to a third party while inside my own API route. The following code does not work because I get the error "Cannot use import statement outside a module." This code is called by a thunk at the front end.
If I can't import axios, what's an alternative?
EDIT: I got rid of the error by doing 'const axios = require('axios') but now the results I'm getting is undefined.
EDIT2: Resolved. Through use of the following:
router.get("/:zip", async (req, res, next) => {
try {
let data = [];
await axios
.get(`https://api.yelp.com/v3/businesses/search`, {
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
location: req.params.zip,
// categories: "coffee",
},
})
.then((response) => {
data = response.data;
});
res.send(data);
} catch (err) {
next(err);
}
});
ORIGINAL CODE WITH ISSUE:
const router = require("express").Router();
module.exports = router;
import axios from "axios";
router.get("/:zip", async (req, res, next) => {
try {
//const restaurants = await Test.findAll({})
const result = await axios.get(
`https://api.yelp.com/v3/businesses/search?location=${req.params.zip}`,
{
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
categories: "coffee",
},
}
).data;
res.send(result);
} catch (err) {
next(err);
}
});
Posted above. It needed a .then snippet.
let data = [];
await axios
.get(`https://api.yelp.com/v3/businesses/search`, {
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
location: req.params.zip,
// categories: "coffee",
},
})
.then((response) => {
data = response.data;
});
res.send(data);

Facing some issues while creating axios interceptor in react native

I am creating an app in react native and using laravel as backend. To manage error globally i am trying to create a axios request interceptor (never create before) which can handle errors but, i am getting error _api.default.get is not a function.
// My Axios Interceptor File
import axios from 'axios';
import {Config} from './common';
import {AsyncStorage} from '#react-native-community/async-storage';
const TIMEOUT = 1 * 60 * 1000;
axios.defaults.timeout = TIMEOUT;
axios.defaults.baseURL = Config.apiUrl;
const axiosInterceptors = async () => {
const token = await AsyncStorage.getItem('token');
const onRequest = config => {
if (token) {
config.headers.common.Authorization = `Bearer ${token}`;
}
return config;
};
const onSuccess = response => {
return response.data;
};
const onError = error => {
return Promise.reject(error);
};
axios.interceptors.request.use(onRequest);
axios.interceptors.response.use(onSuccess, onError);
};
export default axiosInterceptors;
and in my reducer
import axiosInterceptors from "../api"
export const fetchData = () => {
return dispatch => {
axiosInterceptors.get(apiUrl).then(something).catch(something)
}
}
It's work for me
const axiosInterceptors = axios.create({
baseURL: "your base url",
timeout: 500,
headers: {
Accept: "application/json",
Authorization: "Bearer "
}
});
API.interceptors.request.use(
async function(config) {
axios.defaults.timeout = 500;
const token = await AsyncStorage.getItem('token');
config.headers.Authorization = "Bearer ".concat(token);
return config;
},
function(error) {
return Promise.reject(error);
}
);
export default axiosInterceptors;

How to use Async Storage Axios

Problem:
I have create react-native application.And there I am using AsyncStorage with axios in like this to handle my API calls.This is how that looks like.
import axios from "axios";
import { AsyncStorage } from "react-native";
// TODO: Replace this with actual JWT token from Keycloak
axios.defaults.headers.post["Content-Type"] = "application/json";
// Create axios instance for api calls
var instance = null;
export const setAuth = async () => {
const user = await AsyncStorage.getItem("jwt");
AsyncStorage.getItem("jwt").then(token => {
instance = axios.create({
baseURL: "",
timeout: 150000,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json"
}
});
instance.interceptors.response.use(
function(response) {
return response;
},
async function(error) {
if (error.response.status) {
return error;
}
}
);
});
};
export const Get = (route, data) => {
instance || setAuth();
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
);
};
export const Post = (route, data) => {
instance || setAuth();
return instance.post(route, JSON.stringify(data));
};
export const Put = (route, data) => {
debugger;
instance || setAuth();
return instance.put(route, JSON.stringify(data));
};
export const AddAdmin = (route, data) => {};
Becuase of the asynchronus property of AsyncStorage it is not creating the axios instanceinstance = axios.create({.The problem is with after this line .So can someone help me with this.I do not have any idea to find out what is wrong with this. Thank you.
You can give a try to this.
export const setAuth = async () => {
const token = await AsyncStorage.getItem('jwt');
instance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
// remaining Code
};
export const Get = (route, data) => {
function getData(){
return instance.get(
route,
data == null ? { data: {} } : { data: JSON.stringify(data) }
)
}
if(instance) return getData()
return setAuth().then(getData)
}

Check if token still valid before request

I am using an index.js file to make api calls in a vue app. Is there a way to add a catch or a before each call to see if my token is still good and have the user redirected to login if it isnt?
import axios from 'axios'
const client = axios.create({
baseURL : 'http://myapi.com/api/',
json: true
})
export default {
async execute(method, resource, data) {
const token = localStorage.getItem('token')
return client({
method,
url: resource,
data,
crossdomain: true ,
headers: { "Authorization": `Bearer ${token}` }
}).then(req => {
return req.data
})
},
getResponses() {
return this.execute('get', 'GetResponses')
},
getAll(){
return this.execute('get', 'GetAll')
},
You can use an interceptor, where you can pass a function to be called before each request:
const client = axios.create({ baseURL: 'http://myapi.com/api/', json: true });
client.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (isTokenGood(token)) {
return config;
} else {
logout();
}
});
If anyone is interested i ended up going with an interceptor as per #thanksd
My code index.js file in my api folder now looks like this
import axios from 'axios'
import router from '../router'
const client = axios.create({
baseURL : 'http://myapi.com/api/',
json: true
})
client.interceptors.response.use(function (response) {
return response
}, function (error) {
if (error.response.status === 401) {
router.push('/Login')
console.info('auth token expired')
localStorage.clear()
sessionStorage.clear()
} else if (error.response.status === 403) {
router.push('/Login')
} else {
return Promise.reject(error)
}
})
export default {
async execute(method, resource, data) {
const token = localStorage.getItem('token')
return client({
method,
url: resource,
data,
crossdomain: true ,
headers: { "Authorization": `Bearer ${token}` }
}).then(req => {
return req.data
})
},
getResponses() {
return this.execute('get', 'GetResponses')
},
getAll(){
return this.execute('get', 'GetAll')
},