Issue with Vue and Axios: Error retrieving API data using coinmarketcap key

As a beginner in programming, I'm currently working on fetching API data using Axios and Vue.js. However, I'm facing difficulties in passing the data through Axios. Below is the Nodejs code snippet for requesting the API:

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '5000',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c'
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});
This is my vue js file code, I have sent the start and limits because I don't know how

After several attempts that didn't work, here is my first approach:

 <div id="app">
     {{ info }}
    </div>
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue"></script>
    <script>
      let app = new Vue({
  el: '#app',
  data () {
    return {
  info: null
    }
  },
  mounted () {
     let config = {'X-CMC_PRO_API_KEY': 'aaaaaa-bbbbbb-ccccc----ddjjk'};
     axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {headers: config})
     .then(response => (this.info = response))
  }
});
    </script>

Subsequent attempts also did not yield the desired results:

 <div id="app">
     {{ info }}
    </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue"></script>
    <script>
      let app = new Vue({
  el: '#app',
  data () {
    return {
      
  info: null
    }
  },
  mounted () {
     axios
     let config = {'X-CMC_PRO_API_KEY': 'ccccccc'};
      .get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD', {headers: config})
     .then(response => (this.info = response))
  }
});
    </script>

Despite trying different approaches, I still can't figure out what's wrong. Any help or guidance would be greatly appreciated. Thank you in advance.

Answer №1

The reason for this issue is CORS (Cross-Origin Resource Sharing). For more information on how to resolve the CORS error and understand how Access-Control-Allow-Origin works, you can refer to the following article: https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9. One way to address this problem is by implementing a reverse proxy using nginx.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue"></script>
    <title>index</title>
  </head>
  <body>
    <div id="app">
      {{ info }}
    </div>
    <script>
     let app = new Vue({
        el: '#app',
        data () {
          return {
            info: null
          }
        },
        mounted () {
          const API_PROXY = 'https://bird.ioliu.cn/v1/?url='
          axios
              .get(`${API_PROXY}https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=myapikey&start=1&limit=5&convert=USD`)
              .then(response => {
                this.info = JSON.parse(response.data.status.message.response.text)
              })
        }
      })
   </script>
  </body>
</html>

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

What is the best way to incorporate mongoose discriminators?

For my current project, I am looking to utilize mongoose discriminator to manage a collection of users with a specific document structure for the owner. However, I have encountered an error: throw new Error('The 2nd parameter to mongoose.model() shou ...

Altering custom fields in WordPress based on a specified timeline

Just diving into the world of Wordpress and running into a slight dilemma. I have an image that needs its links changed at specific times throughout the day For example, this image on the website should redirect users to abc.com from 8AM to 12PM when clic ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...

Retrieve the input value using jQuery

I'm having trouble retrieving the value from the first name input and passing it to a bootstrap alert when the user clicks the submit button. Below is the code snippet I have been working on: $(document).ready(function() { $("#submit-button").cl ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

Sending Several Parameters to a PHP Script

I'm trying to send multiple JavaScript variables city1 and area1 in a URL to a PHP page by using the code snippet below. However, I seem to be encountering an issue. Can anyone help me figure out what's wrong? $("#list").load("selectcity.php?cit ...

Assurance Code Evaluation

Recently, I've dived into the world of nodeJS and I'm getting acquainted with promises. After looking at the code below, it seems to me that it could be enhanced by integrating the retry logic within getValue2. It's important to note that ...

Encountering issues with HMR after relocating files to the /app directory

Greetings, I am currently in the process of learning how to utilize express with webpacks HMR feature. However, every time I make changes and save a file, I encounter the following error: "The following modules couldn't be hot updated: (Full reload n ...

Unable to control the content within the Repeater DIV

When working inside a repeater's ItemTemplate, I encountered an issue where only the first image/div toggled visibility when the toggle button/link was pressed. The images are dynamically loaded from the database and the toggle function seems to only ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

Is there a way to retrieve a promise from a function that triggers a $http.get request in AngularJS?

Looking for a solution to modify this function: getX: function ($scope) { $http.get('/api/X/GetSelect') .success(function (data) { ... ... }) .error(function (data) { ...

What is the purpose of declaring a variable within a class and then assigning it to "this" in the constructor?

The following code snippet demonstrates the declaration of a variable constObj within the Test class. The object constObj is then assigned to this in the constructor. Why must we declare the variable again when it is already being assigned to this in the ...

Tips on implementing JSON data into select2 plugin

I have been trying to integrate the select2 plugin into my project. I followed a tutorial from this link, but unfortunately, it's not functioning properly for me. Here is the JSON output: [ {"ime":"BioPlex TM"}, {"ime":"Aegis sym agrilla"}, ...

A guide on utilizing ng-repeat to iterate through array values in Views

Need help with using ng-repeat on array values within an ng-repeat in VIEWS? The second ng-repeat is not functioning properly. Here is the value of generalDocument.documents: ["14-10-2015.xls","15-10-2015.xls","16-10-2015.xls"] <div class="box-body ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

How to extract a value from a span input textbox using Vue?

I just started using Vue and I'm attempting to create an auto-growing input. I've realized that it's not possible to create a real <input> element that adjusts its size based on its content and allows for value modifications using v-mo ...

Disable the stack label in a specific column of a stacked column chart using Highcharts

Looking at this stacked column graph in the fiddle link, you'll notice that one column is in grey color to indicate that it is disabled. I am trying to figure out how to hide the total from the top of the column that is grey or belongs to the 'Pe ...