Search code examples
vue.jscorsfiddler

How to use multiple API's in Vue.js


I want to call multiple API's in Vue.js something like this:

<script>
    const app = new Vue({
        el: '#app',
        data: {
            array1: [],
            array2: []
        },
        created(){
            fetch('http://localhost/api/first')
            .then(Response => Response.json())
            .then(json => {
                this.array1 = json
            }),

            fetch('http://localhost/api/second')
            .then(Response => Response.json())
            .then(json => {
                this.array2 = json
            })
        }
    })
</script>

When I use the Vue devtools in Chrome I can see that the 2 arrays are recognised and when I use Fiddler I can see that both the APIs are called. The problem is the second set of JSON results i.e. from http://localhost/api/second don't populate array2.

Any ideas?


Solution

  • Just to answer my own question in case anyone else hits a similar problem. Firstly the code in the question above works fine. My problem was that CORS was not enabled on the server side for the http://localhost/api/second API and it needed to be. Fiddler was not effected by the CORS restriction and hence fetched the API results just fine.