Skip to content

Instantly share code, notes, and snippets.

@deNULL
Last active January 22, 2019 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deNULL/41864312a87edaef9fc37c8e895d662c to your computer and use it in GitHub Desktop.
Save deNULL/41864312a87edaef9fc37c8e895d662c to your computer and use it in GitHub Desktop.

Use axios:

npm install axios --save

src/api.js:

import Vue from 'vue'
const axios = require('axios');

Vue.prototype.$api = new Vue({
  data: {
    endpoint: '//localhost:3000',
    token: '',
  },
  computed: {
    isLoggedIn() {
      return !!this.token;
    }
  },
  methods: {
    projects() {
      return axios.get(`${this.endpoint}/projects`);
    }
  }
});

Then, in src/main.js:

require('./api');

// Useful for debug:
// window.Vue = Vue; 

Now in any Vue component there is this.$api available (await this.$api.projects() to use it).

Testing in browser console (using window.Vue = Vue line): console.table((await Vue.prototype.$api.projects()).data).

Server Side

For Node, using Express:

npm install express --save

And in server.js:

const express = require('express');
const app = express();
const port = 3000;

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT');
  res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// ... any preparations ...

app.get('/projects', (req, res) => {
  res.send(['some data']);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment