VueJs Axios - Managing Request Headers

Edit: Is it possible that this is a CORS issue, considering I am on localhost...

When using Javascript, I have the ability to define request headers and handle responses like this:

    $(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",
        data: "{body}",
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function() {
        alert("error");
    });
});

My Inquiry:

I am interested in learning VueJs and wish to replicate the above functionality using VueJs + Axios. However, I am unsure about how to set the request headers just like in the previous JavaScript code.

Below is my unsuccessful 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 define the request headers as shown in the original JavaScript code? I am eager to understand how to incorporate the following functionality into Vue/Axios.

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

Thank you.

Answer №1

Understanding the variance between the created and mounted events in Vue.js

Explore a solution by utilizing the created() lifecycle hooks rather than relying solely on mounted()

Moreover, you have the option to establish a distinct axios instance for requests featuring a specific header, enhancing your code efficiency:

axios-demo-api.js

import axios from 'axios'

const instance = axios.create({
    baseURL: 'https://demo-api.com',
    headers: {'Ocp-Apim-Subscription-Key': 'YOUR_API_KEY'} //make sure to replace API key with your unique key
})

export default instance

Implementation:

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)
 }
}

Answer №2

The issue does not lie with the header, it seems to be related to the URL construction. Currently, your URL is being formed in this manner:

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

There appears to be a mistake in your URL string as it contains an extra quote at the end, resulting in a 404 error. The correct way to structure your URL is:

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

If you are utilizing Vue instead of jQuery, avoid using $.param and opt for a suitable query string module like qs. Your modified URL should resemble:

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

This approach employs ES2015 string interpolation for improved readability.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

What is the process for incorporating JavaScript-generated coordination into an HTML form?

As a newcomer to Javascript, I am on a mission to integrate geo coordination directly into an HTML form input field. After learning from W3Schools how to generate user latitude and longitude Coordination, I am now eager to input them directly into an HTML ...

Dealing with an event in vue.js is proving to be quite challenging

I encountered an issue while trying to handle an event in vue.js. It seems that the function mm is not within scope, causing the error message [Vue warn]: v-on:mouseover="mm" expects a function value, got undefined. Here is the code snippet: var menuHove ...

Tips for incorporating filtering and sorting functionality in a API-focused application using React and Next.js

In my current project, I am developing a React application using Next.js. The main goal is to fetch data from an API and display cards based on user-selected filters. Specifically, I aim to retrieve the cards initially and then filter them according to the ...

Tips for placing the header text at the center of a TemplateField in your design

I'm using a GridView with TemplateFields. I attempted to align the header text of the TemplateField to center by using HeaderStyle-HorizontalAlign="Center", but it doesn't seem to be working as expected. <asp:TemplateField HeaderTex ...

How can I create clickable table entries using php and html?

I want to create a table on this page that is clickable. When the user clicks on a row, the data from that row will be sent to a PHP file with a form prepopulated with the selected user's information for updating purposes. <!DOCTYPE html> &l ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

Creating a Javascript Regular Expression to detect both accented and non-accented variations of a given string

Is there a way to use regular expressions in JavaScript to match both accented and non-accented versions of a string? I am customizing jQuery-ui's autocomplete feature by adding bold HTML tags around words in the suggestions. Here is my code snippet: ...

The text feature for the Google Places API is not displaying properly within the MUI TextField

For address auto-generation, I am currently utilizing the Google Places API. I have a regular input tag in my HTML where users can type their input and see Google Places suggestions in the dropdown - all working perfectly. However, when I switch to using m ...

The result of combining two JavaScript variables

When I multiply a variable by 2 and assign the value to another variable, why do I get 0? My goal is to toggle the visibility of blocks every time a button is pressed. Oddly enough, it works when I use count++ * 2. For code reference, please refer below: ...

The timing of jQuery's .load function appears to be off, catching us by surprise

My current challenge involves loading returned html from an .aspx page through AJAX, but facing a timing issue with a click event that needs to occur before executing some essential tasks. Specifically, the process begins when a user types in a text field ...

Gain access to a composable data using the defineDefault method in Vue 3 with Vuetify

On numerous pages, I have a component with default props. I am looking to access a composable data (useTheme from vuetify) within the "withDefaults". <script setup lang="ts"> import { ref } from 'vue' import { useTheme } from &apo ...

Dependency of multiple objects in Webgl three.js

I'm struggling with object dependencies and need help. I want to create a setup where one object is dependent on two other objects. Essentially, when I modify the position of one parent object (like changing the y-Position), the dependent object (chil ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

How can I manage file input within a Vue.js application?

After attempting to open a file input with a button, I encountered an issue. When clicking the button, the client reported: “this.$refs.image.click”. Below is my code snippet: <v-btn height="50" ...

Get all the classes from the body element of the AJAX-loaded page and update the body classes on the current page with them

I am currently in the process of AJAX-ing a WordPress theme with a persistent music player. In Wordpress, dynamic classes are used on the <body> tag. The structure I'm working with looks like this: <html> <head> </head> ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

Revamp responsiveness in bootstrap 3 for printing with @media queries

My goal is to disable the responsive features of bootstrap when the event javascript:print() is triggered. This way, I want my webpage to maintain the column grid layout that I have defined, regardless of screen size. One solution suggested in this answer ...