0

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.

wbdlc
  • 1,070
  • 1
  • 12
  • 34
  • Possible duplicate of [How to set header and options in axios?](https://stackoverflow.com/questions/45578844/how-to-set-header-and-options-in-axios) – Vucko Jul 27 '18 at 10:08
  • @Vucko I have used that as a reference point, however this is yielding a 404 response. My concern was, am I going about this wrong? – wbdlc Jul 27 '18 at 10:12
  • I suggest you to think over the usage of jquery + vuejs combo. https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/ – LakiGeri Jul 27 '18 at 12:22
  • @LakiGeri could you elaborate further? Thanks – wbdlc Jul 27 '18 at 12:58

2 Answers2

1

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)
 }
}
vladys.bo
  • 730
  • 2
  • 11
  • 34
  • Thanks, @vladja. I am only starting out learning so appreciate your response here. I amended my code to this snippet, which then returns a 404: https://jsfiddle.net/hx74u851/1/ – wbdlc Jul 27 '18 at 10:55
1

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.

Harshal Patil
  • 17,838
  • 14
  • 60
  • 126