Guest User

Untitled

a guest
Jan 22nd, 2019
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. Use axios:
  2.  
  3. ```bash
  4. npm install axios --save
  5. ```
  6.  
  7. `src/api.js`:
  8.  
  9. ```js
  10. import Vue from 'vue'
  11. const axios = require('axios');
  12.  
  13. Vue.prototype.$api = new Vue({
  14. data: {
  15. endpoint: '//localhost:3000',
  16. token: '',
  17. },
  18. computed: {
  19. isLoggedIn() {
  20. return !!this.token;
  21. }
  22. },
  23. methods: {
  24. projects() {
  25. return axios.get(`${this.endpoint}/projects`);
  26. }
  27. }
  28. });
  29. ```
  30.  
  31. Then, in `src/main.js`:
  32. ```js
  33. require('./api');
  34.  
  35. // Useful for debug:
  36. // window.Vue = Vue;
  37. ```
  38.  
  39. Now in any Vue component there is `this.$api` available (`await this.$api.projects()` to use it).
  40.  
  41. Testing in browser console (using `window.Vue = Vue` line): `console.table((await Vue.prototype.$api.projects()).data)`.
  42.  
  43. ## Server Side
  44.  
  45. For Node, using Express:
  46. ```bash
  47. npm install express --save
  48. ```
  49.  
  50. And in `server.js`:
  51. ```js
  52. const express = require('express');
  53. const app = express();
  54. const port = 3000;
  55.  
  56. app.use(function(req, res, next) {
  57. res.header('Access-Control-Allow-Origin', '*');
  58. res.header('Access-Control-Allow-Credentials', 'true');
  59. res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT');
  60. 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');
  61. next();
  62. });
  63.  
  64. // ... any preparations ...
  65.  
  66. app.get('/projects', (req, res) => {
  67. res.send(['some data']);
  68. });
  69.  
  70. app.listen(port, () => console.log(`Example app listening on port ${port}!`))
  71. ```
Add Comment
Please, Sign In to add comment