What is @nuxtjs/axios?
@nuxtjs/axios is a Nuxt.js module that integrates the Axios HTTP client with Nuxt.js applications. It simplifies making HTTP requests in a Nuxt.js project by providing a consistent API and additional features tailored for Nuxt.js.
What are @nuxtjs/axios's main functionalities?
Making GET Requests
This feature allows you to make GET requests to fetch data from an API endpoint. The example demonstrates how to use the $axios.$get method within the asyncData lifecycle hook to fetch data before rendering the page.
async asyncData({ $axios }) {
const data = await $axios.$get('https://api.example.com/data');
return { data };
}
Making POST Requests
This feature allows you to make POST requests to send data to an API endpoint. The example shows how to use the $axios.$post method to submit form data to a server.
async submitForm({ $axios }, formData) {
const response = await $axios.$post('https://api.example.com/submit', formData);
return response;
}
Setting Base URL
This feature allows you to set a base URL for all Axios requests. The example demonstrates how to configure the base URL in the Nuxt.js configuration file.
export default {
axios: {
baseURL: 'https://api.example.com'
}
}
Handling Errors
This feature allows you to handle errors that occur during HTTP requests. The example shows how to use a try-catch block to catch errors and handle them appropriately within the asyncData lifecycle hook.
async asyncData({ $axios, error }) {
try {
const data = await $axios.$get('https://api.example.com/data');
return { data };
} catch (e) {
error({ statusCode: 500, message: 'Internal Server Error' });
}
}
Other packages similar to @nuxtjs/axios
axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple API for making HTTP requests and is the core library that @nuxtjs/axios is built upon. While @nuxtjs/axios is tailored for Nuxt.js, axios can be used in any JavaScript environment.
vue-resource
Vue-resource is an HTTP client for Vue.js applications. It provides services for making web requests and handling responses using a simple and easy-to-understand API. Compared to @nuxtjs/axios, vue-resource is more tightly integrated with Vue.js but lacks some of the advanced features and flexibility of axios.
fetch
Fetch is a native JavaScript API for making HTTP requests. It is built into modern browsers and provides a more low-level approach compared to axios. While fetch is more lightweight and does not require additional dependencies, it lacks some of the convenience features provided by axios, such as request and response interceptors.
Axios
Use axios with deep Nuxt integration and no pain!
- Automatically set base URL for client & server side
- Injects
$get
,$post
,... into vue context instances so requests can be done easily. - Exposes
setToken
function to $axios
so we can easily and globally set authentication tokens. - Throws nuxt-friendly exceptions and prevent SSR crashes.
- Automatically enables
withCredentials
when requesting to base URL. - Proxy request headers in SSR.
Setup
- Add
@nuxtjs/axios
dependency using yarn or npm to your project - Add
@nuxtjs/axios
module to nuxt.config.js
:
modules: [
'@nuxtjs/axios'
]
Usage
Component asyncData
async asyncData({ app }) {
const {data} = await app.$axios.get('http://icanhazip.com')
return {
ip: data
}
}
Component mixins
You can always access axios instance using this.$axios
.
This mixins are available for easier usage:
this.$request({url: 'http://example.com')
this.$get('http://example.com')
this.$post('http://example.com', { foo: 'bar' })
Example:
async mounted() {
const {data} = await this.$get('http://icanhazip.com')
this.ip = data
}
Store nuxtServerInit
async nuxtServerInit ({ commit }, { app }) {
const { data } = await app.$axios.get('http://icanhazip.com')
commit('SET_IP', data)
}
Store actions
If you need axios instance in store actions, you may have to pass it when dispatching.
export default {
methods: {
updateIP() {
this.$store.dispatch('getIP', { $axios: this.$axios })
}
}
}
{
actions: {
async getIP ({ commit }, { $axios }) {
const { data } = await $axios.get('http://icanhazip.com')
commit('SET_IP', data)
}
}
}
Options
You can pass options using module options or axios
section in nuxt.config.js
:
baseURL
- Default:
http://[HOST]:[PORT]/api
Base URL is required for requests in server-side & SSR and prepended to all requests with relative path.
You can also use environment variable API_URL
which overrides baseURL
.
browserBaseURL
Base URL which is used in client side prepended to all requests with relative path.
You can also use environment variable API_URL_BROWSER
which overrides browserBaseURL
.
- If
browserBaseURL
is not provided it defaults to baseURL
value.
- If hostname & port of
browserbaseURL
are equal to nuxt server, it defaults to relative part of baseURL
.
So if your nuxt application is being accessed under a different domain, requests go to same origin and prevents Cross-Origin problems.
credentials
Adds an interceptor to automatically set withCredentials
config of axios when requesting to baseUrl
which allows passing authentication headers to backend.
In SSR context, sets client request header as axios default request headers.
This is useful for making requests which need cookie based auth on server side.
Also helps making consistent requests in both SSR and Client Side code.
Dynamic API Backend
Please notice that, API_URL
is saved into bundle on build, CANNOT be changed
on runtime! You may use proxy module for dynamically route api requests to different backend on test/staging/production.
Example: (nuxt.config.js
)
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: [
['/api', { target: 'http://www.mocky.io', pathRewrite: { '^/api': '/v2' } }]
]
}
Start Nuxt
[AXIOS] Base URL: http://localhost:3000/api | Browser: /api
[HPM] Proxy created: /api -> http://www.mocky.io
[HPM] Proxy rewrite rule created: "^/api" ~> "/v2"
Now you can make requests to backend: (Works fine in both SSR and Browser)
async asyncData({app}) {
const {data: {nuxt} } = await app.$axios.get('59388bb4120000dc00a672e2')
return {
nuxt
}
}
Details