Onyx
Onyx

Reputation: 5762

How to make GET request on Vue.js using Axios but failing to do so

My Vue project was created using webpack-simple template so I only have main.js and App.vue in my src folder right now. Main.js looks like this:

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

and App.vue looks like this:

<template>
<div id="app">
</div>
</template>

<script>
import axios from 'axios';

axios.defaults.baseURL = 'https://www.bungie.net/Platform';
axios.defaults.headers.common = {
  'X-API-Key': 'ecab73fd6c714d02b64f0c75503671d1'
};

export default {
  axios.get('/User/GetBungieNetUserById/1/')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
  });
}
</script>

<style lang="scss">

</style>

I am following Axios's Github page instructions on how to do the GET request but I seem to be doing something wrong. My goal is to make a GET request to:

https://www.bungie.net/Platform/User/GetBungieNetUserById/1/

which can be done only if I have a X-API-Key header.

For this reason I've set

axios.defaults.baseURL = 'https://www.bungie.net/Platform';
axios.defaults.headers.common = {
  'X-API-Key': 'ecab73fd6c714d02b64f0c75503671d1'
};

And then I'm making the GET request. Sadly I'm getting a failed to compile error:

./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue Module build failed: SyntaxError: C:/MAMP/htdocs/Destiny/src/App.vue: Unexpected token, expected , (14:7)

I'm quite new to Vue so the mistake I am making might be really silly.

Upvotes: 0

Views: 260

Answers (1)

ceejayoz
ceejayoz

Reputation: 179994

Assuming you want to run this code when the Vue component is mounted:

export default {
  mounted() {
    axios.get('/User/GetBungieNetUserById/1/')
    .then(function(response) {
      console.log(response.data);
      console.log(response.status);
    });
  },
}

You can't just slap raw JS in the export default block - Vue expects a component definition, with various properties, some of which may be/contain functions.

Upvotes: 1

Related Questions