Adding Axios package to a Vue 3 project without using the CLI

I'm facing an issue while trying to integrate the Axios package into my Vue 3 project that is not CLI-based. I initially attempted to include the package within the script tags at the top of the page, but that approach failed. Next, I tried creating a new variable for axios and directly passing the URL of the axios package to it, but even that didn't work as expected. How can I properly set up the Axios package in my project?

Below is the code snippet:

<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.tailwindcss.com"></script>

<div id="demo" class="min-h-full bg-gray-200">
<!-- UI -->
</div>

<script>
    const { axios } = "https://unpkg.com/axios/dist/axios.min.js";
    const { onMounted, ref, computed } = Vue
    const app = Vue.createApp({

    const cities = ref()
    
    setup() {
     const getData = async (e) => {
              if (e.key == "Enter") {
              try {
                  const res = await axios.get(
                    `https://api.openweathermap.org/data/2.5/weather?zip={enterzipcodehere},US&appid={youropenweathermapidhere}&units=imperial`
                  )
                  cities.value = res.data.name
                  
                  console.log(cities.value)
                } catch (error) {
                  console.log(error)
                }
              }
        }

     onMounted(() => {
       getData()
     }
    }
})
app.mount('#demo')
</script>

Answer №1

According to the information provided in the installation guide...

If you prefer using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

If you choose unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Once you have added any of those scripts to your HTML page, the global variable for axios will become accessible.


Alternatively, by using a module, you can import the ESM version like so:

<script type="module">
import axios from "https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/esm/axios.min.js";

console.log(
  "todo:",
  (await axios.get("https://jsonplaceholder.typicode.com/todos/1")).data
);
</script>

Answer №2

Simply include the

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
tag in your HTML code, allowing you to access the axios library as a global variable.

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

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

``What is the best way to include a JavaScript jQuery variable value within a PHP array

Let's consider the following scenario: var folderName = jQuery.trim($('#dirname').val()); var parentFolder = jQuery.trim($('#parent').val()); var dynamicUrl = '<?=$this->url(array('controller'=>'index ...

CORS - Preflight request response fails access control verification

I've been attempting to send a GET request to a server with the same domain as my local host, but I keep encountering the following error: The preflight request response fails the access control check: The requested resource does not have an ' ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Using an image for the axis in Wijmo BarGraph

I am currently working with Wijmo barcharts and attempting to create a graph that uses images instead of labels on the x-axis. The code I have at the moment displays the image source as a string rather than displaying the actual image. Does anyone know ho ...

Sending arrays in JSON format using Node.js Express (res.json)

I have a code snippet like this: app.get('/orders/:pizzeriaID/:status', async (req, res) => { try { const requestedOrderByPizzeriaID = req.params['pizzeriaID']; const requestedOrderByStatus = req.params['status']; ...

Sidebar-driven top navigation menu

I am currently developing a Single Page Application using VueJS along with vuerouter. In my App.vue file, the structure is as follows: <template> <div id="app"> <header><topbar></topbar></header> <div cl ...

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

Activate video in Slick Slider with the click of a button

I am facing an issue with my slider setup, where each slide contains a video as the background along with play/pause buttons. When I try to play the video by clicking the corresponding button on a specific slide, I encounter this problem: if I click the pl ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Utilizing Vue router: a guide to sending data to the default route

Below is the configuration of my vue router: [ { name: 'home', path: '/', component: HomeComponent, props: true, }, { name: 'detail', path: '/detail/:id', ...

What is the best approach for creating a brute-force solution for finding the smallest change algorithm

Looking for a solution to this algorithm challenge: Create a function that can determine the minimum amount of change that cannot be made with the given coins. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) ...

Is it possible to access the Windows certificate store using JavaScript?

Is there a way to access the Windows certificate store using JavaScript? I'm looking to create a web application that can validate user logins by reading their certificates. ...

a new approach for creating a conditional function in pointfree fashion

Can someone help me convert this code into a pointfree style? To provide context: The function receives an Array of Either types and returns a Task type. If any of the Either types have the left set, the Task type is rejected with that value. If none of t ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...