Home » vue » VueJs Axios – Request headers

VueJs Axios – Request headers

Posted by: admin November 26, 2021 Leave a comment

Questions:

Edit: Could this be a CORS issue, I’m on localhost…

In Javascript I can set the request headers and get and return a response like so:

    $(function() {
    var params = {
        // Request parameters
    };

    $.ajax({
        url: "https://demo-api.com/",
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{API KEY}");
        },
        type: "GET",
        // Request body
        data: "{body}",
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function() {
        alert("error");
    });
});

Question:

I want to learn VueJs and would like replicate this with VueJs + Axios, however I am confused as to how to set the request headers as I have in the above JS.

Here is my failed attempt:

    new Vue({
      el: '#app',
      data () {
        return {
          info: null,
          loading: true,
          errored: false,
          response: false
        }
      },
      mounted () {
          axios({
              method: 'get',
              url: 'https://demo-api.com/',
              headers: { 
                'Ocp-Apim-Subscription-Key': 'API KEY',
              } 
            })
            .then(response => {
              console.log(response)
              this.response = true
            })
            .catch(error => {
              console.log(error)
              this.errored = true
            })
            .finally(() => this.loading = false)
        }
    })

How can I specifically set the request headers as I have in the above JS. I am wanting to learn how to implement the below in Vue/Axios.

 xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{API KEY}");

Thanks.

Answers:

Difference between the created and mounted events in Vue.js

Read an answer and try to use created() lifecycle hooks instead of mounted()

Furthermore, you can create separate instance of axios for request with this header and then use it inn you code:

axios-demo-api.js

import axios from 'axios'

const instance = axios.create({
    baseURL: 'https://demo-api.com',
    headers: {'Ocp-Apim-Subscription-Key': 'API KEY'} //don't forget to change API key to your exact key
})

export default instance

Usage:

import axiosInstance from 'axios-demo-api';


export default {

 created() {
  axiosInstance.get('/{demoId}?' + $.param(params))
                .then(response => {
              console.log(response)
              this.response = true
            })
            .catch(error => {
              console.log(error)
              this.errored = true
            })
            .finally(() => this.loading = false)
 }
}

###

Your problem is not the header. You are setting it properly. It has to do with the URL. You are constructing your URL like this:

url: 'https://demo-api.com/{demoId}?" + $.param(params)',

Your URL string is wrong. It has an extra quote at the end. That’s why you got 404 error. This is what you need to do:

url: "https://demo-api.com/{demoId}?" + $.param(params),

Also, if you are using Vue and not jQuery, then you should not use $.param function. Instead, use a proper query string module like qs. So your actual URL would be like:

url: `https://demo-api.com/${demoId}?${qs.stringify(params)}`,

Here we are using ES2015 string interpolation.