Omegon
Omegon

Reputation: 471

Why is the data not retrieved from axios Promise using await?

I am making a post request using axios:

const instance = axios.create({
    baseURL: "http://localhost:8080",
    headers: {
      "Content-Type": "application/json",
    },
});

instance.interceptors.response.use((response) => {
    return response
  }, async function (error) {
    const originalRequest = error.config;
    if (error.response.status === 403 && !originalRequest._retry) {
      originalRequest._retry = true;
      const access_token = await refreshAccessToken();            
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
      return instance(originalRequest);
    }
    return Promise.reject(error);
});

const getToken = async () =>{
    const userData = {
      login: login,
      password: password,
    };
    const responce = await instance.post("http://localhost:8080/login", userData,{headers: { 'Content-Type': 'application/json' }});
    return responce;
}

Now when I'm trying to get an answer:

const data = getToken();

enter image description here

A Promise is always returned, which contains the necessary data inside, but how do I get just data without a Promise?

i also try:

const responce = await instance.post("http://localhost:8080/data", userData,{headers: { 'Content-Type': 'application/json' }})
.tnen((responce) => responce.data);

But nothing changes.

Upvotes: 0

Views: 38

Answers (1)

jarmod
jarmod

Reputation: 78908

Here is a simplified example of how to make calls with Axios and get JSON responses:

const axios = require("axios");

const instance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com",
  headers: {
    "Content-Type": "application/json",
  },
});
    
const postData = async (data) => {
  return instance.post("https://jsonplaceholder.typicode.com/posts", data);
};

// An async IIFE
(async () => {
  const response = await postData({ id: 100, title: "Yellow submarine" });
  const data = response.data;
  console.log(data);
})();

The printed result is:

{ id: 101, title: 'Yellow submarine' }

Upvotes: 1

Related Questions