Socket
Socket
Sign inDemoInstall

@nuxtjs/axios

Package Overview
Dependencies
3
Maintainers
3
Versions
86
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuxtjs/axios


Version published
Weekly downloads
136K
decreased by-18.1%
Maintainers
3
Created
Weekly downloads
 

Package description

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

Changelog

Source

5.0.0-alpha.1 (2018-01-28)

Features

  • integrate with nuxt progress bar (41a0964)

<a name="5.0.0-alpha.0"></a>

Readme

Source


Axios

Secure and Easy Axios integration with Nuxt.js.

📖 Release Notes

If you are coming from an older release please be sure to read Migration Guide

Features

✓ Automatically set base URL for client & server side

✓ Exposes setToken function to $axios so we can easily and globally set authentication tokens

✓ Throws nuxt-friendly errors and optionally redirect on specific error codes

✓ Automatically enables withCredentials when requesting to base URL

✓ Proxy request headers in SSR (Useful for auth)

✓ Fetch Style requests

✓ Automatically integrate with Nuxt.js progress bar

Table of Contents

Setup

Install with yarn:

yarn add @nuxtjs/axios

Install with npm:

npm install @nuxtjs/axios

nuxt.config.js

{
  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    // proxyHeaders: false
  }
}

Usage

Component

asyncData

async asyncData({ app }) {
  const ip = await app.$axios.$get('http://icanhazip.com')
  return { ip }
}

methods/created/mounted/etc

methods: {
  async fetchSomething() {
    const ip = await this.$axios.$get('http://icanhazip.com')
    this.ip = ip
  }
}

Store nuxtServerInit

async nuxtServerInit ({ commit }, { app }) {
  const ip = await app.$axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}

Store actions

// In store
{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}

Extending Axios

If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.

nuxt.config.js

  modules: [
    '@nuxtjs/axios',
  ],
  plugins: [
    '~/plugins/axios'
  ]

plugins/axios.js

export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })

  $axios.onError(error => {
    if (error.code === 400) {
      redirect('/400')
    }
  })
}

Helpers

Interceptors

Axios plugin provides helpers to register axios interceptors easier and faster.

  • onRequest(config)
  • onResponse(response)
  • onError(err)
  • onRequestError(err)
  • onResponseError(err)

This functions don't have to return anything by default.

Example: (plugins/axios.js)

export default function ({ $axios, redirect }) {
  $axios.onError(error => {
    if(error.code === 500) {
      redirect('/sorry')
    }
  })
}

Fetch Style requests

Axios plugin also supports fetch style requests with $ prefixed methods:

// Normal usage with axios
let data = (await $axios.get('...')).data

// Fetch Style
let data = await $axios.$get('...')

setHeader(name, value, scopes='common')

Axios instance has a helper to easily set any header.

Parameters:

  • name: Name of the header
  • value: Value of the header
  • scopes: Send only on specific type of requests. Defaults
    • Type: Array or String
    • Defaults to common meaning all types of requests
    • Can be get, post, delete, ...
// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')

// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')

// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
  'post'
])

// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])

setToken(token, type, scopes='common')

Axios instance has an additional helper to easily set global authentication header.

Parameters:

  • token: Authorization token
  • type: Authorization token prefix(Usually Bearer).
  • scopes: Send only on specific type of requests. Defaults
    • Type: Array or String
    • Defaults to common meaning all types of requests
    • Can be get, post, delete, ...
// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')

// Overrides `Authorization` header with new value
this.$axios.setToken('456')

// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')

// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])

// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)

Options

You can pass options using module options or axios section in nuxt.config.js

prefix, host and port

This options are used for default values of baseURL and browserBaseURL.

Can be customized with API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) environment variables.

Default value of prefix is /.

baseURL

  • Default: http://[HOST]:[PORT][PREFIX]

Base URL which is used and prepended to make requests in server side.

Environment variable API_URL can be used to override baseURL.

browserBaseURL

  • Default: baseURL (or prefix when options.proxyMode is true)

Base URL which is used and prepended to make requests in client side.

Environment variable API_URL_BROWSER can be used to override browserBaseURL.

progress

  • Default: true

Integrate with Nuxt.js progress bar to show a loading bar while making requests. (Only on browser, when loading bar is available.)

credentials

  • Default: false

Adds an interceptor to automatically set withCredentials config of axios when requesting to baseUrl which allows passing authentication headers to backend.

debug

  • Default: false

Adds interceptors to log request and responses.

proxyHeaders

  • Default: true

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.

NOTE: If directing requests at a url protected by CloudFlare's CDN you should set this to false to prevent CloudFlare from mistakenly detecting a reverse proxy loop and returning a 403 error.

proxyHeadersIgnore

  • Default ['host', 'accept']

Only efficient when proxyHeaders is set to true. Removes unwanted request headers to the API backend in SSR.

License

MIT License - Copyright (c) 2017 Nuxt Community

FAQs

Last updated on 28 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc