简体   繁体   中英

axios.get not returning JSON

I'm learning the Vue.js framwork at the moment. More specific, Using Axios to Consume APIs.

I have this code:

var app = new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      //.get('http://calapi.inadiutorium.cz/api/v0/en/calendars/general-en.json')
      .then(response => (this.info = response))
  }
})

The axios.get('https://api.coindesk.com... line is working correctly. Unfortunately, the second (commented) line is not.

Is there someone who can tell me why there's no response with the commented line?

Code: https://codepen.io/anon/pen/zJdvzW

Thanks in advance.

It is because of the cors. You can install Google Chrome plugin called CORS and enable it. This will allow your axios call to work.

Codepen uses https but you are trying to access resource on a website that uses http , as you can see in console:

spread.js:25 Mixed Content: The page at ' https://codepen.io/anon/pen/OojyYR ' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ' http://calapi.inadiutorium.cz/api/v0/en/calendars/general-en.json '. This request has been blocked; the content must be served over HTTPS.

If you use jsfiddle instead of codepen it will work: http://jsfiddle.net/eywraw8t/335825/

Also, your requested resource is inside of response.data

The response data can be retrieved from response.data .

api.coindesk.com doesn't have a CORS issue because it already includes Access-Control-Allow-Origin: * header.

change your code to:

axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response.data))

Looking at the network request being made you see it fails due to a blocked mixed-content flag 网络请求的屏幕截图

A little digging suggest this may be due to the fact that the call is via http rather than https which unfortunately can only be fixed by the creator of the API. As a result the browser is failing to make the request as it's seeing the response as insecure. Read more here .

This doesn't really answer the question unfortunately, if the request was made from a backend it may not be so sensitive to the mixed-content but within the browser you may struggle to get results from this API. (For instance calling from postman the api response is passed with no issue)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM