N
N
Nikita Andreevich2020-05-08 06:53:17
API
Nikita Andreevich, 2020-05-08 06:53:17

How to receive and send token in axios?

Good day to all. Please tell me what I'm doing wrong? I've been sitting for several hours, tried everything ..
I get an error Error: Request failed with status code 401 .

I received the token (already began to doubt that it was right ..), now when I make a request to the server to receive data, and insert it into the header token , I get 401

Class for working with api

import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

export default class City {
  //Auth and get token
  getToken = async params => {
    const req = await axios.post(
      'https://api',
      params,
    );

    const token = await JSON.stringify(req.data.access_token);
    await AsyncStorage.setItem('userToken', token);
    return token;
  };

  // get data Account
  getInfo = async token => {

    const req = await axios.get(
      'http://api',
      {headers: {Authorization: `Bearer ${token}`}},
    );

    const info = await JSON.stringify(req.data);
    return info;
  };
}


// function that makes a request to the server and receives a token
import City from '../../api';

export default class Login extends React.Component{

city = new City();

onSubmit = async () => {

    const params = new URLSearchParams();
    params.append('username', email);
    params.append('password', password);

    this.city
      .getToken(params)
      .then(item => {
        console.log(item);
      })
      .catch(error => {
        console.log(`${error} -ERROR`);
      });
  };

}


// function that makes a request to the server to get data
import City from '../../api';


export default class Main extends React.Component{

city = new City();

  componentDidMount() {
    this.asyncData();
  }

  asyncData = async () => {
    const {authUser} = this.props;

    const token = await AsyncStorage.getItem('userToken');
    await authUser(token);
    this.getInfo(token);
  };

  getInfo = token => {
    this.city
      .getInfo(token)
      .then(item => {
        console.log(`GET INFO ------------${item}`);
      })
      .catch(error => {
        console.log(`ERROR -------------${error}`);
      });
  };
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pastukhov, 2020-05-08
@NikitosAndreevich

const req = await axios.get(
  'http://api',
  { headers }, // <-- скобки
 );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question