performing a request to Axios API with the inclusion of ${item} within the URL

I am having trouble with calling axios in Vuetify due to backticks and ${} within the URL. I believe I need to convert it into JSON format, but my attempts have been unsuccessful. Could you please provide an explanation?

Here is the code snippet. Whenever I click on the Search button, the console displays the following error:

[Vue warn]: Error in v-on handler: 'ReferenceError: term is not defined'
<div id="app">
  <v-app >
    <v-form >
      <v-row class="app">
        <v-col class="text-center" cols="12" sm="4">
             <v-text-field
              placeholder="Find Book"
            ></v-text-field>
          <div class="my-2">
            <v-btn v-on:click="getBooks" large color="primary">Search</v-btn>
          </div>
        </v-col>
      </v-row>
      </v-form>
  </v-app>
  <!-- You may use this container for your listing -->
  <div>
    
  </div>
</div>
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  
  components: {},
  data(){
    return{
      books: []
    }
  },
  methods: {
    getBooks: function() {
      const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`;
      const obj = JSON.parse(apiUrl)
 
      axios.get("obj")
        .then(function (resp) {
        this.books = resp.data
        console.log(this.books)
      })
    },
  }    
});

Answer №1

When using template literals (enclosing strings in backticks), placeholders can be inserted with ${term}, which can include expressions or variables. In this specific scenario, the error occurs because there is no variable named "term" within the current scope.

There is no need to apply JSON.parse() to apiUrl as it is not formatted in JSON. Instead, pass apiUrl directly into axios.get():

const term = 'Moby Dick';
const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`;
axios.get(apiUrl).then(...)

new Vue({
  el: '#app',
  data: () => ({
    books: [],
  }),
  methods: {
    getBooks() {
      const term = 'Moby Dick'
      const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`
      axios.get(apiUrl).then(resp => {
        this.books = resp.data
      })
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfa9aaba9fedf1e9f1eeed">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53322b3a3c2013637d61637d63">[email protected]</a>/dist/axios.min.js"></script>

<div id="app">
  <button @click="getBooks">Get books</button>
  <pre>{{ books }}</pre>
</div>

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

Sophisticated solution for html5 video fallback with JavaScript

My Django website allows users to upload videos in mp4 format for others to watch. However, there are cases where certain browsers cannot play this format, like Firefox. In such scenarios, I want to provide a fallback option to download the video instead o ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

Next.js API Endpoint Call Resulting in Empty Object Returned by Fetch Function

Having an issue with making an API call in Next.js to delete an item from the database. I'm using the "body" field of the fetch to send a string to the API. The fetch call is within a Next.JS page, and the API endpoint is located in the API folder gen ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...

When you use ReactDOM.render inside a <div>, it does not instantly generate HTML code

I am currently working with React version 16.7 and attempting to embed React components into a third-party JavaScript library (specifically, Highcharts) that requires me to output HTML from a function. This is the approach I am taking at the moment: funct ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

AngularJS POST request encounters failure: Preflight response contains improperly formatted HTTP status code 404

I have encountered a persistent issue with microframeworks while attempting to perform a simple POST request. Despite trying multiple frameworks, none of them seem to handle the POST request properly: Here is an example using AngularJS on the client side: ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

Recommendations for Configuring VPS for Angular2 and .Net Application

My team and I are currently in the process of developing an application that combines Angular2 for the front-end and Web API ASP.NET for the back-end. We are currently at the stage of configuring a VPS for this application but unfortunately, we lack the ...

Concealing website links in the browser's address bar

Running my own website on a personal server with Ubuntu server, I noticed that my public IP address is displayed in the status bar when visitors browse my site or hover over links. Even after purchasing a domain name from godaddy, I couldn't find an o ...

What is the best approach for iterating through the creation of Objects?

Here is a simplified version of the current code, with fewer rows and properties. var row1 = new Object(); var row2 = new Object(); var row3 = new Object(); var row4 = new Object(); var row5 = new Object(); var row6 = new Object(); var row7 = new Object() ...

symfony submit form without sending request

I'm trying to make a request without using a submit button, only by selecting an option. So far, I've attempted to achieve this using JavaScript but haven't had any success. Here's my form code: $form = $this->createFormBuilder() ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

Manipulate SVG elements with JavaScript to embed a PNG image into the SVG file

Is it possible to edit an SVG, such as changing the fill color and other SVG methods? I am also looking to insert an SVG/PNG within another SVG at a specific path or group. Can someone provide guidance on how to achieve this? ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

Tips for preventing 404 errors in react-router

I am currently working on a project using React Router and created it using create-react-app. Everything runs smoothly on my local server with links like localhost:3000/login and localhost:3000/product. However, when I deployed the project to my domain, ...