0

I wanted to create a function that receives parameters that Axios can use to make a request. In my login file I want to get my JWT token in a variable.

My login file where the function is called:

async function doSomething() {
  await Request("post", "api/auth/local", {
   "identifier": "test@mail.nl",
   "password": "Test1234"
 })
 .then((res) => {
     console.log(res);
     
 })
 .catch(error => {
     console.log(error)
 });
 }
 doSomething()

The file that receives the parameters:

const Request = async (method, url, data) => {
    
  const token = sessionStorage.getItem("token");

  axios.defaults.baseURL = "http://localhost:1337/";
  axios.defaults.headers.post["Content-Type"] = "application/json";

  if (method && url && data) {
    const config = {
      method: method,
      url: url,
      data: data
    };
    console.log(method, url, data)

     await axios(config)
      .then((response) => {
        console.log("Succes!");
        console.log(response.data);
        return response.data
      })
      .catch((error) => {
        console.log(data)
        console.log(error)
      });
      
  }
}

I saw on an another post someone using .then after using the function but it outputs undefined.

when I try to catch the output from the function into a var like this for example:

const data = Request("post", "api/auth/local", {
  data: data
})

I get a promise... but I want to get the value

  • `const data = await Request(` A little saying worth remembering, _once_async_always_async_ – Keith Nov 10 '22 at 14:51

0 Answers0