Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Use axios:
- ```bash
- npm install axios --save
- ```
- `src/api.js`:
- ```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`:
- ```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:
- ```bash
- npm install express --save
- ```
- And in `server.js`:
- ```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}!`))
- ```
Add Comment
Please, Sign In to add comment