Retrieve the header tag from API using Nuxt

I am trying to dynamically set OG:Tags using an API

head() {
this.$axios
  .get(`............`)
  .then((response) => {
    this.og_title = response.data.message.course.course_name;
    this.og_description = response.data.message.course.description;
    this.og_image = response.data.message.course.img_url;

    console.log(this.og_title);
    return {
      title: this.title,
      meta: [
        {
          property: "og:title",
          content: this.og_title,
        },
        {
          property: "og:description",
          content: this.og_description,
        },
        {
          property: "og:image",
          content: this.og_image,
        }
      ]
    };
  });

However, despite printing correctly in the console, the tags do not show up when testing on production.

Answer №1

It is recommended to make Axios requests (and any other asynchronous calls) within the asyncData method. asyncData will seamlessly integrate its returned value into your component's internal state, allowing you to access this data using this.

Keep in mind that asyncData is specifically designed for components located in the pages folder.

Here is an example utilizing the @nuxt/http library:

<script>
  export default {
    async asyncData({ params, $http }) {
      const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
      return { post }
    },
    head() {
      return {
        title: this.post.title,
        meta: [
          {
            property: "og:title",
            content: this.post.title,
          },
          {
            property: "og:description",
            content: this.post.description,
          },
          {
            property: "og:image",
            content: this.post.image,
          },
        ],
      };
    }
  }
</script>

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

Tips for implementing a live filter on an HTML table using JavaScript without the need to refresh the webpage

I successfully implemented these table filtering codes using plain JavaScript that I found on W3schools. The code filters table data based on input text and includes a select dropdown for additional filtering options. However, I encountered some issues whe ...

Deciphering the GWT compiler's results

Although I'm not a JavaScript developer, I'm currently delving into the process of converting Java code to JS using the GWT compiler in order to identify the root cause of memory growth in our extensive application. Every now and then, I come ac ...

Can Mustache syntax {{}} be used to inject a Vue component?

I am dealing with a markdown file that includes YAML frontmatter. Within the frontmatter, I am trying to reference a component like so: --- title: Hello world component: <component-a></component-a> --- Lorem ipsum... My goal is to reference th ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Is it possible to count the number of days in between and then apply a specific class to each of those days

Here is the code snippet that I am working with: <div class="row"> <div class="test">02/12/2013</div> <div class="test">03/12/2013</div> <div class="test">04/12/2013</div> <div class="test"> ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Utilize jQuery to invoke an ASP page method from an HTML page

I have a static web page named index.html which includes text boxes for data input. My goal is to send this data to an ASP page called Default.aspx using jQuery/AJAX. I attempted the following: $.ajax({ url: "Default.aspx/GetData", ...

Tips for passing a variable from one function to another file in Node.js

Struggling to transfer a value from a function in test1.js to a variable in test2.js. Both files, test.js and test2.js, are involved but the communication seems to be failing. ...

Issue with Vue template not displaying within a loop

After completing a basic Vue tutorial on setting up a Todo app, I decided to integrate some aspects of it into a website I am developing. However, I have encountered an issue with my for-loop that is not functioning as expected. The project was initially ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...

A guide to retrieving the authorization header from a URL within a Vue JS application

I recently built a Vue.js application for frontend development. In our scenario, we need to retrieve authentication information in the authorization header from another web application. I'm a bit confused on how to access the authorization header fr ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

Identify the quantity of dynamically added <li> elements within the <ul> using jQuery

I'm facing an issue where I need to dynamically add a list of LI items to a UL using jQuery. However, when I try to alert the number of LI elements in this list, it only shows 0. I suspect that it's because the code is trying to count the origina ...

Obtaining the category value within a slot of the Vuetify calendar

I am struggling to implement hover functionality in the categories view of Vuetify calendar within the body section (slot day-body). When I try to add hover functionality, the entire row ends up being affected by the hover effect, even though I only want i ...

Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database. I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

I have a JavaScript code stored as a string that I need to transform into plain JavaScript

If I have a variable in string format, for example suppose there is a JavaScript code inside it: var string="function myFunction(a,b){return a*b;}"; I want to convert this into pure JavaScript code format like so: function myFunction(a, b) { return ...

Bring in a JavaScript file from Blogger without using a tag

Is there a way to retrieve blogger feeds code without using <script src=? I attempted to achieve this using document.write, but it resulted in the deletion of the original page content upon import. Is there an alternate method to import when triggering ...

Retrieve or update the selected option value in a Select2 multiple dropdown

I'm currently using Select2 for multiselect on an input field. My goal is to identify which choice has been clicked, but when I inspect the event triggered upon clicking a choice ("choice-selected"), all I see is event.target.value which contains the ...