'Can't Login user using Axios in React Native
I am new to React Native so bear with me. I am attempting to create a login for my app using Axios but keep running into the same error. Some of my code is listed below. I was able to run my API through postman just fine but can seem to get it to work here. My API is through bubble.io. Everything looks like it's set up correctly there since it works with Post Man but I wanted to make sure I wasn't missing something obvious in the code.
fetch.js
import { API_URL } from '../secrets';
import { getToken } from './token';
const getHeaders = async () => {
const token = await getToken();
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return headers;
};
export const post = async (destination, body) => {
const headers = await getHeaders();
const result = await fetch(`${API_URL}${destination}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
console.log(response.data);
if (result.ok) {
return await result.json();
}
throw { error: result.status };
};
export const get = async (destination) => {
const headers = await getHeaders();
const result = await fetch(`${API_URL}${destination}`, {
method: 'GET',
headers,
});
if (result.ok) {
return await result.json();
}
throw { error: result.status };
};
authentication.js
import { post } from './fetch';
export const login = (email, password) => {
return post('/login', {
user: { email, password },
});
};
export const createAccount = (email, password) => {
return post('/users', {
user: { email, password },
});
};
token.js
import AsyncStorage from '@react-native-async-storage/async-storage'
export const getToken = async () => {
try {
const value = await AsyncStorage.getItem('@auth_token');
if (value !== null) {
return value;
}
} catch (e) {
return null;
}
};
export const setToken = async (token) => {
try {
await AsyncStorage.setItem('@auth_token', token);
} catch (e) {
return null;
}
};
LoginScreen.js
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import { login } from '../../api/authentication';
import EmailForm from '../../forms/EmailForm';
const LoginScreen = ({ navigation }) => {
return (
<EmailForm
buttonText="Log in"
onSubmit={login}
onAuthentication={() => navigation.navigate('Menu')}
>
<Button
title="Create account"
onPress={() => navigation.navigate('CreateAccount')}
/>
</EmailForm>
);
};
export default LoginScreen;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
