Categories
Vue

Make HTTP Requests in a Vue App with vue-resource — More Requests

The vue-resource library is a useful HTTP client library for Vue apps.

It’s a good alternative to Axios for making requests.

In this article, we’ll look at how to use it to make HTTP requests with a Vue app.

Setting Request Headers and Query Parameters Per Request

We can set headers per request by setting the headers property of the request object.

To set the query string parameters, we can put them in the object we set as the value of the params property.

For example, we can write:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const { bodyText } = await this.$http.get("https://api.agify.io", {
      params: { name: "michael" },
      headers: { Accept: "application/json" }
    });
    this.response = JSON.parse(bodyText);
  }
};
</script>

Resource

We can use the this.$resource property to make different requests with the same base URL.

For example, we can write:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const resource = this.$resource(
      "https://jsonplaceholder.typicode.com/posts{/id}"
    );
    const getResponse = await resource.get({ id: 1 });
    console.log(getResponse);

    const saveResponse = await resource.save(
      {},
      { title: "foo", body: "bar", userId: 1 }
    );
    console.log(saveResponse);
  }
};
</script>

We called the this.$resource method with the base URL to return a resource object that we can call.

{/id} is a placeholder for the URL parameter.

Then we can call resource.get to make a GET request.

And resource.save makes a POST request. The first argument is an object with the URL parameter values.

The 2nd argument is the request body.

The query method also makes a GET request.

The update method makes a PUT request.

And the delete or remove method makes a DELETE request.

For example, we can call query by writing:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const resource = this.$resource(
      "https://jsonplaceholder.typicode.com/posts{/id}"
    );
    const getResponse = await resource.query({ id: 1 });
    console.log(getResponse);
  }
};
</script>

To make a PUT request, we can write:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const resource = this.$resource(
      "https://jsonplaceholder.typicode.com/posts{/id}"
    );
    const updateResponse = await resource.update(
      { id: 1 },
      {
        title: "foo",
        body: "bar",
        userId: 1
      }
    );
    console.log(updateResponse);
  }
};
</script>

The argument is the same as the other methods.

To make a DELETE request, we can write:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const resource = this.$resource(
      "https://jsonplaceholder.typicode.com/posts{/id}"
    );
    const removeResponse = await resource.remove({ id: 1 });
    console.log(removeResponse);
  }
};
</script>

or:

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const resource = this.$resource(
      "https://jsonplaceholder.typicode.com/posts{/id}"
    );
    const removeResponse = await resource.delete({ id: 1 });
    console.log(removeResponse);
  }
};
</script>

Conclusion

We can make requests easily in a Vue app with the vue-resource library.

Categories
Vue

Make HTTP Requests in a Vue App with vue-resource

The vue-resource library is a useful HTTP client library for Vue apps.

It’s a good alternative to Axios for making requests.

In this article, we’ll look at how to use it to make HTTP requests with a Vue app.

Installation

We can install the library by running:

yarn add vue-resource

or

npm install vue-resource

It can also be included with a script tag:

<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>

Making Requests

To make a request, we register the plugin in main.js by writing:

import Vue from "vue";
import App from "./App.vue";
import VueResource from "vue-resource";

Vue.use(VueResource);
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App)
}).$mount("#app");

Then to make the request, we write:

<template>
  <div id="app">{{response}}</div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const { bodyText } = await this.$http.get(
      "https://api.agify.io//?name=michael"
    );
    this.response = JSON.parse(bodyText);
  }
};
</script>

We call this.$http.get to make a get request to an endpoint.

To make a post request, we can write:

<template>
  <div id="app">{{response}}</div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const { bodyText } = await this.$http.post(
      "https://jsonplaceholder.typicode.com/posts",
      {
        title: "foo",
        body: "bar",
        userId: 1
      }
    );
    this.response = JSON.parse(bodyText);
  }
};
</script>

We just pass the request body into the 2nd argument.

Getting Response

We can get the response header from the headers property:

"<template>
  <div id="app">{{response}}</div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const response = await this.$http.post(
      "https://jsonplaceholder.typicode.com/posts",
      {
        title: "foo",
        body: "bar",
        userId: 1
      }
    );
    console.log(response.headers.get("Expires"));
    this.response = JSON.parse(response.bodyText);
  }
};
</script>

We pass the header key to the get method to get its value.

Getting a Blob

We can get a blob with the this.$http.get method to get a blob.

All we have to do is set the responseType to 'blob' :

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

<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const response = await this.$http.get(
      "https://picsum.photos/id/23/200/300",
      { responseType: "blob" }
    );
    const blob = await response.blob();
    console.log(blob);
  }
};
</script>

Interceptors

We add an interceptor to set the request header for all requests.

We can set the request headers globally by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import VueResource from "vue-resource";

Vue.use(VueResource);
Vue.config.productionTip = false;
Vue.http.interceptors.push((request) => {
  request.headers.set("X-CSRF-TOKEN", "TOKEN");
  request.headers.set("Authorization", "Bearer TOKEN");
});

new Vue({
  render: (h) => h(App)
}).$mount("#app");

App.vue

<template>
  <div id="app">{{response}}</div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      response: {}
    };
  },
  async beforeMount() {
    const { bodyText } = await this.$http.post(
      "https://jsonplaceholder.typicode.com/posts",
      {
        title: "foo",
        body: "bar",
        userId: 1
      }
    );
    this.response = JSON.parse(bodyText);
  }
};
</script>

We have the Vue.http.interceptors.push method to modify requests with the request.headers.set method.

Conclusion

We can use the vue-resource library to make requests in a Vue app.

Categories
Vue

Make HTTP Requests in a Vue App with Axios — Handling Errors and Cancellation

Axios is a popular HTTP client that is used with Vue apps.

In this article, we’ll look at how to make requests with Axios in a Vue app.

Removing Interceptors

We can remove request or response interceptors with the eject method.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
const interceptor = axios.interceptors.response.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/posts/1"
    });
    console.log(data);
    axios.interceptors.request.eject(interceptor);
  }
};
</script>

to cal the eject method to remove the interceptor.

Add Interceptor to a Custom Instance of Axios

We can add a request or response interceptor to a custom instance of Axios.

To do that, we write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

const instance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/posts",
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" }
});

instance.interceptors.response.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await instance.get("/1");
    console.log(data);
  }
};
</script>

We just call instance.interceptors.response.use to add the interceptor to the Axios instance.

We can replace response with request to add a request interceptor to an instance.

Handling Errors

To handle errors, we can catch them. For instance, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    try {
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1"
      );
      console.log(data);
    } catch (error) {
      if (error.response) {
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log("Error", error.message);
      }
      console.log(error.config);
    }
  }
};
</script>

We can check if the error is from the response or the request with the response and request properties.

The message property has the error message.

The config property has the config.

We can also validate the status with a function. Axios will only resolve if the status is what we want.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    try {
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1",
        {
          validateStatus(status) {
            return status < 500;
          }
        }
      );
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  }
};
</script>

to add the validateStatus method to resolve the promise returned by axios.get if the status code is less than 500.

Cancellation

To make a request cancellable, we can use a cancel token.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

export default {
  name: "App",
  async beforeMount() {
    try {
      source.cancel("Operation canceled by the user.");
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1",
        {
          cancelToken: source.token
        }
      );
      console.log(data);
    } catch (thrown) {
      if (axios.isCancel(thrown)) {
        console.log("Request canceled", thrown.message);
      } else {
        // handle error
      }
    }
  }
};
</script>

We call the source.cancel method to cancel the request. The argument is the message to show.

axios.isCancel method lets us check if the request is canceled or not.

thrown.message has the message we passed into the argument.

Conclusion

We can handle errors and make requests cancellable with Axios.

Categories
Vue

Make HTTP Requests in a Vue App with Axios

Axios is a popular HTTP client that is used with Vue apps.

In this article, we’ll look at how to make requests with Axios in a Vue app.

Installation

We can install the package by running:

npm i axios

Also, we can add the library with a script tag. Either we can write:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

or:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Making Requests

To make a request with Axios, we just call the methods that come with the library.

For example, to make a GET request, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
    console.log(data);
  }
};
</script>

We pass in the URL to the get method to make a GET request.

To make a POST request, we can use the POST method:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios.post(
      "https://jsonplaceholder.typicode.com/posts",
      {
        title: "foo",
        body: "bar",
        userId: 1
      }
    );
    console.log(data);
  }
};
</script>

The 2nd argument is the request body.

The axios object can also be called directly to make a request.

To make a GET request, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "post",
      url: "https://jsonplaceholder.typicode.com/posts",
      data: {
        title: "foo",
        body: "bar",
        userId: 1
      }
    });
    console.log(data);
  }
};
</script>

We have the method property that sets the request method.

url has the request URL.

data has the request body.

To make a GET request, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/posts/1"
    });
    console.log(data);
  }
};
</script>

Axios Instance

We can create our own Axios object with the axios.create method:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
const instance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/posts",
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" }
});

export default {
  name: "App",
  async beforeMount() {
    const { data } = await instance.get("/1");
    console.log(data);
  }
};
</script>

We set the base URL of the requests with the baseURL property.

Also, we can set the headers, timeout, and other request parameters.

Then we call get with the URL relative to the baseURL and get the data .

Interceptors

We can add interceptors for requests and responses. For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
axios.interceptors.request.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/posts/1"
    });
    console.log(data);
  }
};
</script>

We call axios.interceptors.request.use to call intercept requests.

To intercept responses, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
axios.interceptors.response.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/posts/1"
    });
    console.log(data);
  }
};
</script>

Conclusion

We can make HTTP requests with Axios in our Vue app.

Categories
Vue

Add Metadata to our Vue App with vue-meta

To add meta tags easily in our Vue app, we can use the vue-meta library.

In this article, we’ll look at how to use the Vue Meta library to let us add meta tags to our Vue app.

Installation

We can install it by running:

yarn add vue-meta

or

npm i vue-meta

Also, we can include the library directly with a script tag.

The dev version can be added by writing:

<script src="https://unpkg.com/vue-meta/dist/vue-meta.js"></script>

and the production version can be added by writing:

<script src="https://unpkg.com/vue-meta/dist/vue-meta.min.js"></script>

Adding the Meta Tags

To add the tags, we have to register the plugin.

To do that, we write:

import Vue from "vue";
import App from "./App.vue";
import VueMeta from "vue-meta";

Vue.use(VueMeta);
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App)
}).$mount("#app");

in main.js to add the plugin.

We can also add an object with some options as the 2nd argument:

import Vue from "vue";
import App from "./App.vue";
import VueMeta from "vue-meta";

Vue.use(VueMeta, {
  keyName: "metaInfo",
  attribute: "data-vue-meta",
  ssrAttribute: "data-vue-meta-server-rendered",
  tagIDKeyName: "vmid",
  refreshOnceOnNavigation: true
});
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App)
}).$mount("#app");

keyName is the name of the component option that has all the information to convert to meta tags and attributes.

attributre is the name of the attribute to let vue-meta know how it should manage and ignore.

ssrAttribute is the name of the attribute that’s added to the html tag to inform vue-meta that the server has generated the meta tag.

tagIDKeyName is the property that tells vue-meta to overwrite an item in a tag list.

refreshOnceOnNavigation pauses update once page navigation starts and resume updates when navigation finishes when it’s true .

It can help improve speed and fix flickering when replacing styles.

Once we have registered the plugin, we can add the metaInfo property to add the meta tags:

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

<script>
export default {
  name: "App",
  metaInfo: {
    title: "App Title",
    titleTemplate: "%s | My Awesome Webapp"
  }
};
</script>

The title property adds the title that will be replaced with the placeholder.

This means 'App Title' will replace the %s placeholder to form the text content of the title tag.

We can add the style tag to the head with vue-meta. For example, we can write:

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

<script>
export default {
  name: "App",
  metaInfo: {
    style: [
      {
        vmid: "page-load-overlay",
        innerHTML: `
          body div.loading {
            z-index: 999;
            background-color: yellow;
            opacity: 0.9;
          }
        `
      }
    ]
  },
  data() {
    return {
      cssTexts: []
    };
  },
  mounted() {
    this.cssTexts.push({
      vmid: "page-load-overlay",
      innerHTML: null
    });
  }
};
</script>

We set the style property to an object with the values.

Also, we can load the styles dynamically:

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

<script>
export default {
  name: "App",
  metaInfo() {
    const style = this.cssTexts;
    return { style };
  },
  data() {
    return {
      cssTexts: []
    };
  },
  mounted() {
    this.cssTexts.push({
      vmid: "page-load-overlay",
      innerHTML: `
        body div.loading {
          z-index: 999;
          background-color: yellow;
          opacity: 0.9;
        }
      `
    });
  }
};
</script>

The this.cssTexts.push pushes the style.

Conclusion

We can add metadata to the head tag with the vue-meta library.