Socket
Socket
Sign inDemoInstall

@nuxtjs/axios

Package Overview
Dependencies
Maintainers
3
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuxtjs/axios - npm Package Compare versions

Comparing version 4.5.2 to 5.0.0-alpha.0

lib/module.js

21

CHANGELOG.md

@@ -5,2 +5,23 @@ # Change Log

<a name="5.0.0-alpha.0"></a>
# [5.0.0-alpha.0](https://github.com/nuxt-community/axios-module/compare/v4.5.2...v5.0.0-alpha.0) (2018-01-28)
### Code Refactoring
* a better and more stable way to specify baseURL and browserBaseURL options ([533cf4e](https://github.com/nuxt-community/axios-module/commit/533cf4e))
### Features
* interceptor helpers ([fa3eb47](https://github.com/nuxt-community/axios-module/commit/fa3eb47))
* rewrite plugin ([647b58f](https://github.com/nuxt-community/axios-module/commit/647b58f))
### BREAKING CHANGES
* prefix should be set to `/api` for backward compability. refer to new docs.
<a name="4.5.2"></a>

@@ -7,0 +28,0 @@ ## [4.5.2](https://github.com/nuxt-community/axios-module/compare/v4.5.1...v4.5.2) (2017-12-29)

261

lib/plugin.template.js
import Axios from 'axios'
// We cannot extend Axios.prototype
const axiosExtraProto = {}
// Sets a common header
axiosExtraProto.setHeader = function setHeader (name, value, scopes = 'common') {
if(!Array.isArray(scopes)) {
scopes = [scopes]
}
scopes.forEach(scope => {
if (!value) {
delete this.defaults.headers[scope][name];
return
// Axios.prototype cannot be modified
const axiosExtra = {
setHeader (name, value, scopes = 'common') {
for (let scope of Array.isArray(scopes) ? scopes : [ scopes ]) {
if (!value) {
delete this.defaults.headers[scope][name];
return
}
this.defaults.headers[scope][name] = value
}
this.defaults.headers[scope][name] = value
})
}
// Set requests token
axiosExtraProto.setToken = function setToken (token, type, scopes = 'common') {
},
setToken (token, type, scopes = 'common') {
const value = !token ? null : (type ? type + ' ' : '') + token
this.setHeader('Authorization', value, scopes)
},
onRequest(fn) {
this.interceptors.request.use(config => fn(config) || config)
},
onResponse(fn) {
this.interceptors.response.use(response => fn(response) || response)
},
onRequestError(fn) {
this.interceptors.request.use(undefined, error => fn(error) || Promise.reject(error))
},
onResponseError(fn) {
this.interceptors.response.use(undefined, error => fn(error) || Promise.reject(error))
},
onError(fn) {
this.onRequestError(fn)
this.onResponseError(fn)
}
}
// Request helpers
const reqMethods = [
'request', 'delete', 'get', 'head', 'options', // url, config
'post', 'put', 'patch' // url, data, config
]
reqMethods.forEach(method => {
axiosExtraProto['$' + method] = function () {
return this[method].apply(this, arguments).then(res => res && res.data)
}
})
// Request helpers ($get, $post, ...)
for (let method of ['request', 'delete', 'get', 'head', 'options', 'post', 'put', 'patch']) {
axiosExtra['$' + method] = function () { return this[method].apply(this, arguments).then(res => res && res.data) }
}
// Setup all helpers to axios instance (Axios.prototype cannot be modified)
function setupHelpers( axios ) {
for (let key in axiosExtraProto) {
axios[key] = axiosExtraProto[key].bind(axios)
const extendAxiosInstance = axios => {
for (let key in axiosExtra) {
axios[key] = axiosExtra[key].bind(axios)
}
}
const redirectError = <%= serialize(options.redirectError) %>
<% if (options.debug) { %>
const log = (level, ...messages) => console[level]('[Axios]', ...messages)
// Set appreciate `statusCode` and `message` to error instance
function errorHandler(error, ctx) {
if (error.response) {
// Error from backend (non 2xx status code)
// ...Auto redirect on special status codes
if (redirectError[error.response.status]) {
ctx.redirect(redirectError[error.response.status])
}
error.statusCode = error.statusCode || parseInt(error.response.status) || 500
error.message = error.message || error.response.statusText || (error.statusCode + ' (Internal Server Error)')
} else if (error.request) {
// Error while making request
error.statusCode = error.statusCode || 500
error.message = error.message || 'request error'
} else {
// Something happened in setting up the request that triggered an Error
error.statusCode = error.statusCode || 0
error.message = error.message || 'axios error'
}
const setupDebugInterceptor = axios => {
// request
axios.onRequestError(error => {
log('error', 'Request error:', error)
})
return Promise.reject(error)
// response
axios.onResponseError(error => {
log('error', 'Response error:', error)
})
axios.onResponse(res => {
log(
'info',
'[' + (res.status + ' ' + res.statusText) + ']',
'[' + res.config.method.toUpperCase() + ']',
res.config.url)
if (process.browser) {
console.log(res)
} else {
console.log(JSON.stringify(res.data, undefined, 2))
}
return res
})
}
<% if (options.errorHandler) { %>
const customErrorHandler = <%= serialize(options.errorHandler).replace('errorHandler(', 'function(').replace('function function', 'function') %>
<% } %>
<% if(options.debug) { %>
function debug(level, messages) {
if (!(console[level] instanceof Function)) {
level = 'info'
messages = arguments
} else {
level = arguments[0]
messages = Array.prototype.slice.call(arguments, 1)
}
if (!messages.length) {
console[level].call(null, '[@nuxtjs/axios] <empty debug message>')
} else {
for (var i = 0; i < messages.length; i++) {
console[level].call(null, messages[i])
<% if (options.credentials) { %>
const setupCredentialsInterceptor = axios => {
// Send credentials only to relative and API Backend requests
axios.onRequest(config => {
if (config.withCredentials === undefined) {
if (!/^https?:\/\//i.test(config.url) || config.url.indexOf(config.baseURL) === 0) {
config.withCredentials = true
}
}
}
})
}
<% } %>
// Setup BaseURL
const baseURL = process.browser
? (process.env.API_URL_BROWSER || '<%= options.browserBaseURL %>')
: (process.env.API_URL || '<%= options.baseURL %>')
export default (ctx, inject) => {
const axiosOptions = {
// baseURL
baseURL : process.browser
? (process.env.API_URL_BROWSER || '<%= options.browserBaseURL %>')
: (process.env.API_URL || '<%= options.baseURL %>'),
// Custom init hook
<% if (options.init) { %>
const initHook = <%= serialize(options.init).replace('init(', 'function(').replace('function function', 'function') %>
<% } %>
export default <% if (options.init) { %>async<% } %>(ctx, inject) => {
const { req } = ctx
// Create a fresh objects for all default header scopes
// Axios creates only one which is shared across SSR requests!
// https://github.com/mzabriskie/axios/blob/master/lib/defaults.js
const headers = {
common : {
'Accept': 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
// Create fresh objects for all default header scopes
// Axios creates only one which is shared across SSR requests!
// https://github.com/mzabriskie/axios/blob/master/lib/defaults.js
headers: {
common : {
'Accept': 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
}
}
<% if(options.proxyHeaders) { %>
// Default headers
headers.common = (req && req.headers) ? Object.assign({}, req.headers) : {}
<% for (let h of options.proxyHeadersIgnore) { %>delete headers.common['<%= h %>']
<% if (options.proxyHeaders) { %>
// Proxy SSR request headers headers
axiosOptions.headers.common = (ctx.req && ctx.req.headers) ? Object.assign({}, ctx.req.headers) : {}
<% for (let h of options.proxyHeadersIgnore) { %>delete axiosOptions.headers.common['<%= h %>']
<% } %><% } %>
// Create new axios instance
const axios = Axios.create({
baseURL,
headers
})
const axios = Axios.create(axiosOptions)
<% if (options.credentials) { %>
// Send credentials only to relative and API Backend requests
axios.interceptors.request.use(config => {
if (config.withCredentials === undefined) {
if (!/^https?:\/\//i.test(config.url) || config.url.indexOf(baseURL) === 0) {
config.withCredentials = true
}
}
return config
});
<% } %>
// Extend axios proto
extendAxiosInstance(axios)
<% if(options.debug) { %>
// Debug
axios.interceptors.request.use(config => {
debug('[@nuxtjs/axios] Request:', config)
return config
}, error => {
debug('error', '[@nuxtjs/axios] Error:', error)
return Promise.reject(error)
});
axios.interceptors.response.use(config => {
debug('[@nuxtjs/axios] Response:', config)
return config
}, error => {
debug('error', '[@nuxtjs/axios] Error:', error)
return Promise.reject(error)
});
<% } %>
// Setup interceptors
<% if (options.debug) { %>setupDebugInterceptor(axios) <% } %>
<% if (options.credentials) { %>setupCredentialsInterceptor(axios)<% } %>
<% if (options.requestInterceptor) { %>
// Custom request interceptor
const reqInter = <%= serialize(options.requestInterceptor).replace('requestInterceptor(', 'function(').replace('function function', 'function') %>
axios.interceptors.request.use(config => reqInter(config, ctx))
<% } %>
<% if (options.responseInterceptor) { %>
// Custom response interceptor
const resInter = <%= serialize(options.responseInterceptor).replace('responseInterceptor(', 'function(').replace('function function', 'function') %>
axios.interceptors.response.use(config => resInter(config, ctx))
<% } %>
// Error handler
<% if (options.errorHandler) { %>
// Custom error handler
axios.interceptors.response.use(undefined, err => customErrorHandler(err, ctx))
<% } else if (options.disableDefaultErrorHandler === false) { %>
axios.interceptors.response.use(undefined, err => errorHandler(err, ctx));
<% } %>
// Inject axios to the context as $axios
ctx.$axios = axios
inject('axios', axios)
<% if (options.init) { %>
await initHook(axios, ctx)
<% } %>
// Setup axios helpers
setupHelpers(axios)
}
{
"name": "@nuxtjs/axios",
"version": "4.5.2",
"version": "5.0.0-alpha.0",
"description": "Secure and easy axios integration with Nuxt.js",
"license": "MIT",
"main": "lib/index.js",
"main": "lib/module.js",
"repository": "https://github.com/nuxt-community/axios-module",

@@ -12,2 +12,3 @@ "publishConfig": {

"scripts": {
"dev": "nuxt test/fixture",
"lint": "eslint lib src test",

@@ -39,7 +40,6 @@ "test": "npm run lint && jest",

"chalk": "^2.3.0",
"debug": "^3.1.0",
"whatwg-url": "^6.4.0"
"debug": "^3.1.0"
},
"devDependencies": {
"nuxt": "^1.0.0-rc11",
"nuxt": "^1.1.1",
"codecov": "^3.0.0",

@@ -46,0 +46,0 @@ "eslint": "^4.14.0",

@@ -33,47 +33,49 @@ <p align="center">

If you are coming from an older release please be sure to read [Migration Guide](https://github.com/nuxt-community/axios-module/wiki/Migration-guide)
# Table of Contents
- [Features](#features)
- [Setup](#setup)
- [Usage](#usage)
- [Component](#component)
- [Store](#store-nuxtserverinit)
- [Store Actions](#store-actions)
- [Options](#options)
- [browserBaseURL](#browserbaseurl)
- [credentials](#credentials)
- [debug](#debug)
- [proxyHeaders](#proxyheaders)
- [proxyHeadersIgnore](#proxyheadersignore)
- [redirectError](#redirecterror)
- [requestInterceptor](#requestinterceptor)
- [responseInterceptor](#responseinterceptor)
- [init](#init)
- [disableDefaultErrorHandler](#disabledefaulterrorhandler)
- [errorHandler](#errorhandler)
- [Helpers](#helpers)
- [Fetch Style Requests](#fetch-style-requests)
- [Set Header](#setheadername-value-scopescommon)
- [Set Token](#settokentoken-type-scopescommon)
- [Dynamic API Backend](#dynamic-api-backend)
* [Features](#features)
* [Setup](#setup)
* [Usage](#usage)
* [Component](#component)
* [Store](#store-nuxtserverinit)
* [Store Actions](#store-actions)
* [Extending Axios](#extending-axios)
* [Helpers](#helpers)
* [Interceptors](#interceptors)
* [Fetch Style Requests](#fetch-style-requests)
* [Set Header](#setheadername-value-scopescommon)
* [Set Token](#settokentoken-type-scopescommon)
* [Options](#options)
* [Prefix, Host and Port](#prefix-host-and-port)
* [baseURL](#baseurl)
* [browserBaseURL](#browserbaseurl)
* [credentials](#credentials)
* [debug](#debug)
* [proxyHeaders](#proxyheaders)
* [proxyHeadersIgnore](#proxyheadersignore)
* [disableDefaultErrorHandler](#disabledefaulterrorhandler)
## 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 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
## Setup
Install with npm:
Install with yarn:
```bash
>_ npm install @nuxtjs/axios
>_ yarn add @nuxtjs/axios
```
Install with yarn:
Install with npm:
```bash
>_ yarn add @nuxtjs/axios
>_ npm install @nuxtjs/axios
```

@@ -97,3 +99,3 @@

### Component
### Component

@@ -121,2 +123,3 @@ **`asyncData`**

### Store `nuxtServerInit`
```js

@@ -130,3 +133,2 @@ async nuxtServerInit ({ commit }, { app }) {

### Store actions
(Needs Nuxt >= 1.0.0-RC8)

@@ -145,126 +147,58 @@ ```js

## Options
You can pass options using module options or `axios` section in `nuxt.config.js`
## Extending Axios
### `baseURL`
- Default: `http://[HOST]:[PORT]/api`
If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.
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`.
**nuxt.config.js**
### `browserBaseURL`
- Default: `/api`
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`
- Default: `true`
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 all responses and requests
### `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.
### `redirectError`
- Default: `{}`
This option is a map from specific error codes to page which they should be redirect.
For example if you want redirecting all `401` errors to `/login` use:
```js
axios: {
redirectError: {
401: '/login'
}
}
modules: [
'@nuxtjs/axios',
],
plugins: [
'~/plugins/axios'
]
```
### `requestInterceptor`
- Default: `null`
**plugins/axios.js**
Function for manipulating axios requests. Useful for setting custom headers,
for example based on the store state. The second argument is the nuxt context.
```js
requestInterceptor: (config, { store }) => {
if (store.state.token) {
config.headers.common['Authorization'] = store.state.token
}
return config
export default function ({ $axios, redirect }) {
$axios.onRequest(config => {
console.log('Making request to ' + config.url)
})
}
```
### `responseInterceptor`
- Default: `null`
## Helpers
```js
responseInterceptor: (response, ctx) => {
return response
}
```
### Interceptors
Axios plugin provides helpers to register axios interceptors easier and faster.
Function for manipulating axios responses.
- `onRequest(config)`
- `onResponse(response)`
- `onError(err)`
- `onRequestError(err)`
- `onResponseError(err)`
### `init`
- Default: `null`
This functions don't have to return anything by default.
Function `init(axios, ctx)` to do additional things with axios. Example:
Example: (`plugins/axios.js`)
```js
axios: {
init(axios, ctx) {
axios.defaults.xsrfHeaderName = 'X-CSRF-TOKEN'
}
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if(error.code === 500) {
redirect('/sorry')
}
})
}
```
### `disableDefaultErrorHandler`
- Default: `false`
### Fetch Style requests
If you want to disable the default error handler for some reason, you can do it so
by setting the option `disableDefaultErrorHandler` to true.
Axios plugin also supports fetch style requests with `$` prefixed methods:
### `errorHandler`
- Default: (Return promise rejection with error)
Function for custom global error handler.
This example uses nuxt default error page.
If you define a custom error handler, the default error handler provided by this package will be overridden.
```js
axios: {
errorHandler (errorReason, { error }) {
error('Request Error: ' + errorReason)
}
},
```
## Helpers
### Fetch Style requests
Axios plugin also supports fetch style requests with `$` prefixed methods:
```js
// Normal usage with axios

@@ -278,12 +212,14 @@ let data = (await $axios.get('...')).data

### `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`, ...
* **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`, ...
```js

@@ -297,3 +233,5 @@ // Adds header: `Authorization: 123` to all requests

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

@@ -305,12 +243,14 @@ // Removes default Content-Type header from `post` scope

### `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`, ...
* **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`, ...
```js

@@ -333,52 +273,62 @@ // Adds header: `Authorization: 123` to all requests

## Dynamic API Backend
Please notice that, `API_URL` is saved into bundle on build, CANNOT be changed
on runtime! You may use [proxy](../proxy) module for dynamically route api requests to different backend on test/staging/production.
## Options
**Example: (`nuxt.config.js`)**
You can pass options using module options or `axios` section in `nuxt.config.js`
```js
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: [
['/api', { target: process.env.PROXY_API_URL || 'http://www.mocky.io', pathRewrite: { '^/api': '/v2' } }]
]
}
```
### `prefix`, `host` and `port`
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"
```
This options are used for default values of `baseURL` and `browserBaseURL`.
Now you can make requests to backend: (Works fine in both SSR and Browser)
```js
async asyncData({ app }) {
// Magically makes request to http://www.mocky.io/v2/59388bb4120000dc00a672e2
const nuxt = await app.$axios.$get('59388bb4120000dc00a672e2')
Can be customized with `API_PREFIX`, `API_HOST` (or `HOST`) and `API_PORT` (or `PORT`) environment variables.
return {
nuxt // -> { nuxt: 'Works!' }
}
}
```
Default value of `prefix` is `/`.
Details
- `'@nuxtjs/axios'`
- By default axios plugin sets base url to `http://[host]:[port]/api` which is `http://localhost:3000/api`
### `baseURL`
- `'/api': 'http://www.mocky.io/v2'`
- This line creates a server middleware to pass requests from `/api` to `http://www.mocky.io/v2`
- We used `pathRewrite` to remove `/api` from starting of requests and change it to `/v2`
- For more information and advanced usage please refer to [proxy](https://github.com/nuxt-community/modules/blob/master/packages/proxy) docs.
* 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`.
### `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](./LICENSE)
Copyright (c) 2017 Nuxt Community
[MIT License](./LICENSE) - Copyright (c) 2017 Nuxt Community
SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc