0

I send a request to the API for creating an account(I use axios) then API send me a response involve a token. I save this token in local storage.But I don't know how to send it in axios header.

if (this.sendRequest) {
    axios.post(url, data)
      .then((res) => {
        if (res.data.type === "success") {
         localStorage.setItem("token",res.data.data);
        }
      })
      .catch((err) => this.msg.push("error" + err.response.status));
  }
  • Maybe you can check this https://stackoverflow.com/questions/44245588/how-to-send-authorization-header-with-axios? – Leau Dec 09 '21 at 21:02

1 Answers1

0

To do this, follow the steps below:

1- create a folder in your project called Services. Then create another directory in that folder called Config. Inside that folder create a .js file called auth-axios.js as follows: enter image description here

In this file, you use the following code. By doing this, you inform the application that every time you want to call the API, you must go through this port and you must set the base URL and header in the API automatically:

import axios from "axios";
import authService from "../modules/authService";
import Vue from "vue";

const headers = {
  "content-type": "application/json",
  Accept: "application/json",
  "Accept-Language": "fa",
  version: "1000"
};

const API_V1 = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL_V1,
  headers: headers
});

const API_DEV = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL_DEV,
  headers: headers
});

API_DEV.interceptors.request.use(
  config => {
    const token = authService.getAccessToken();
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

export { API_V1, API_V4, API_DEV };

Now for the services that you have in the application, you have to create a separate file in the same services directory and use the API_1 variable in that file.

for example, create accountServices.js and on this file call API by this way:

import { API_V1 } from "../config/auth-axios";

class employerServices {

  createAccount(body) {
    return API_V1.post("test-API-URL", body);
  }
}

export default new employerServices();