Home > Blockchain >  how can i add headers in vue js using async/await
how can i add headers in vue js using async/await

Time:07-17

i'm trying to send a request to the backend which uses headers, please how can i add the headers

this is my script tag

<script>
import axios from "axios";
export default {
  data: () => ({
    fullName: "",
    streetAddress1: ""
  }),
  created() {
    //user is not authorized
    if (localStorage.getItem("token") === null) {
      this.$router.push("/login");
    }
  },
 
  methods: {
    
    async onAddAddress() {
       const token = localStorage.getItem("token");
          headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer"   token,
          "x-access-token": token
        }
      try {
        let data = {
          fullName: this.fullName,
          streetAddress: this.streetAddress1
        };
   const response = axios
          .post("http://localhost:5000/api/addresses", data)
          .then(res => {
            
            console.log(res);
            
          });

        console.log(response);
      } catch (error) {
        console.error("error >>", error);
      }
    }
  }
 }

this code gives me an error, please how can i go about this

CodePudding user response:

There are a few problems with your code. For instance you do not define headers as a variable and you do not add it to your axios request as a third argument. I think you need something like this:

 async onAddAddress() {
    
     const token = localStorage.getItem("token");

     /// define headers variable
     const headers = { 
         "Content-Type": "application/json",
         Authorization: "Bearer"   token,
         "x-access-token": token
     };

     let data = {
        fullName: this.fullName,
        streetAddress: this.streetAddress1
     };
     
     try {
        /// config as the third argument.
        conts result = await axios.post("http://localhost:5000/api/addresses", data, { headers });
     
        console.log(result);
     }
     catch (error) {
        console.error("error >>", error)      
     }

 }

For async/await to work, you need to add await in front of the axios call.

Hope this helps.

  • Related