Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@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 0.0.1 to 1.0.0

16

CHANGELOG.md

@@ -6,3 +6,19 @@ # Change Log

<a name="1.0.0"></a>
# 1.0.0 (2017-05-26)
### Features
* initial migration to 1.0.0-alpha1 ([05c1b7a](https://github.com/nuxt/modules/commit/05c1b7a))
### BREAKING CHANGES
* New modules system is backward incompatible with nuxt-helpers style modules
<a name="0.0.1"></a>
## 0.0.1 (2017-05-10)

38

index.js
const chalk = require('chalk')
const path = require('path')
function printURL (title, url, prefix) {
/* eslint-disable no-console */
console.log(chalk.bgMagenta.black(` ${title} `) + chalk.magenta(` ${url}${prefix}`) + '\r\n')
}
module.exports = function nuxtAxios(options) {
// Register plugin
this.addPlugin({src: path.resolve(__dirname, 'plugin.js'), options})
module.exports = (nuxt) => {
// API URL
const API_URL = process.env.API_URL || process.env.npm_package_config_nuxt_api_url || 'http://localhost:3000'
// API URL
const API_URL = options.API_URL || process.env.API_URL || 'http://localhost:3000'
process.env.API_URL = API_URL
// API URL for Browser
const API_URL_BROWSER = process.env.API_URL_BROWSER || process.env.npm_package_config_nuxt_api_url_browser || API_URL
// API URL for Browser
const API_URL_BROWSER = options.API_URL_BROWSER || process.env.API_URL_BROWSER || API_URL
process.env.API_URL_BROWSER = API_URL_BROWSER
// Common API Prefix
const API_PREFIX = process.env.API_PREFIX || process.env.npm_package_config_nuxt_api_prefix || '/api'
// Common API Prefix
const API_PREFIX = options.API_PREFIX || process.env.API_PREFIX || '/api'
process.env.API_PREFIX = API_PREFIX
nuxt.env.API_PREFIX = API_PREFIX
// Don't add env to production bundles
// Don't add env to production bundles
if (process.env.NODE_ENV !== 'production') {
nuxt.env.API_URL = API_URL
nuxt.env.API_URL_BROWSER = API_URL_BROWSER
this.options.env.API_URL = API_URL
this.options.env.API_URL_BROWSER = API_URL_BROWSER
}

@@ -31,3 +28,3 @@

if (API_URL_BROWSER && API_URL_BROWSER.length > 0) {
if (API_URL_BROWSER !== API_URL) {
printURL('API URL (Browser)', API_URL_BROWSER, API_PREFIX)

@@ -37,6 +34,7 @@ }

module.exports.meta = {
name: 'nuxt-axios',
plugin: path.resolve(__dirname, 'plugin.js'),
vendor: ['axios']
function printURL(title, url, prefix) {
/* eslint-disable no-console */
console.log(chalk.bgMagenta.black(` ${title} `) + chalk.magenta(` ${url}${prefix}`) + '\r\n')
}
module.exports.meta = require('./package.json')
{
"name": "@nuxtjs/axios",
"version": "0.0.1",
"version": "1.0.0",
"license": "MIT",

@@ -5,0 +5,0 @@ "main": "index.js",

@@ -8,109 +8,85 @@ import Axios from 'axios'

// Create new axios instance
const axios = Axios.create({
baseURL: API_URL + (process.env.API_PREFIX || '/api')
})
// Try to get axios from components context, fallback to global Axios else
function getAxios() {
return (this && this.$root && this.$root.$options.$axios) ? this.$root.$options.$axios : Axios
}
// Throw nice http errors & keep SSR safe
function onError (e) {
if (!inBrowser) {
return {}
// Vue Component Mixins
Vue.mixin({
computed: {
$axios() {
return getAxios.call(this)()
}
},
methods: {
// opts
$request(opts) {
return getAxios.call(this).request(opts);
},
// url, opts
$get(url, opts) {
return getAxios.call(this).get(url, opts);
},
$delete(url, opts) {
return getAxios.call(this).delete(url, opts);
},
$head(url, opts) {
return getAxios.call(this).head(url, opts);
},
// url, data, opts
$post(url, data, opts) {
return getAxios.call(this).post(url, data, opts);
},
$put(url, data, opts) {
return getAxios.call(this).put(url, data, opts);
},
$patch(url, data, opts) {
return getAxios.call(this).patch(url, data, opts);
}
}
})
let response = {}
if (e.response) {
response = e.response.data
// Send credentials only to relative and API Backend requests
const withCredentials = config => {
if (config.withCredentials === undefined) {
if (!/^https?:\/\//i.test(config.url) || config.url.indexOf(process.env.API_URL_BROWSER) === 0 || config.url.indexOf(process.env.API_URL) === 0) {
config.withCredentials = true
}
}
throw Object.assign({
statusCode: 500,
message: 'Request error'
}, response)
return config
}
// Wap promise
function wrapPromise (p) {
return p.then(res => {
return res.data || {}
}).catch(onError)
// Nuxt friendly http errors
const handleError = error => {
// const response = error.response || {}
// const config = error.config || {}
// TODO: Add integration with vue notification and nuxt.$error
// Avoid promise rejections in SSR context
return inBrowser? Promise.reject(error) : error
}
// Opts Enhancer
function wrapOpts (opts = {}, _url) {
const url = _url || opts.url || ''
if (opts.withCredentials === undefined) {
// Send credentials only to relative and API Backend requests
if (!/^https?:\/\//i.test(url) || url.indexOf(process.env.API_URL_BROWSER) === 0 || url.indexOf(process.env.API_URL) === 0) {
opts.withCredentials = true
}
// Set requests token
function setToken(token, type = 'Bearer') {
if (!token) {
delete this.defaults.headers.common.Authorization;
return
}
return opts
this.defaults.headers.common.Authorization = (type ? type + ' ' : '') + token
}
// Create wrappers
// https://github.com/mzabriskie/axios#request-method-aliases
export const $request = function (opts) {
return wrapPromise(axios.request(wrapOpts(opts)))
}
export default ({app}) => {
// Create new axios instance
const axios = Axios.create({
baseURL: API_URL + (process.env.API_PREFIX || '/api')
})
export const $get = function (url, opts) {
return wrapPromise(axios.get(url, wrapOpts(opts, url)))
}
// Setup instance interceptors
axios.interceptors.request.use(withCredentials);
axios.interceptors.response.use(undefined, handleError);
export const $delete = function (url, opts) {
return wrapPromise(axios.delete(url, wrapOpts(opts, url)))
}
// Make accessible using {this,$nuxt}.$root.$options.$axios
app.$axios = axios
export const $head = function (url, opts) {
return wrapPromise(axios.head(url, wrapOpts(opts, url)))
// setToken helper
axios.setToken = setToken.bind(axios)
}
export const $post = function (url, data, opts) {
return wrapPromise(axios.post(url, data, wrapOpts(opts, url)))
}
export const $put = function (url, data, opts) {
return wrapPromise(axios.put(url, data, wrapOpts(opts, url)))
}
export const $patch = function (url, data, opts) {
return wrapPromise(axios.patch(url, data, wrapOpts(opts, url)))
}
// ----------------------------------------
// Vue Plugin
// ----------------------------------------
const VueAxios = {
install (Vue) {
// Globally register as $http
Vue.prototype.$http = axios
// Mixins
Vue.mixin({
methods: {
$request,
$get,
$delete,
$head,
$post,
$put,
$patch
}
})
}
}
// ----------------------------------------
// Install vue plugin
// ----------------------------------------
Vue.use(VueAxios)
// ----------------------------------------
// setToken module
// ----------------------------------------
export const setToken = function (token) {
axios.defaults.headers.common.Authorization = token ? `Bearer ${token}` : null
}

@@ -1,35 +0,41 @@

## Axios
This plugin is a wrapper around [axios](https://github.com/mzabriskie/axios). It tries to resolve and make easier lot's of ajax tasks specially with SSR.
So you can use **$get('profile')** instead of `(await Axios.get('http://server/api/profile')).data`.
# Axios
This plugin is a wrapper around [axios](https://github.com/mzabriskie/axios).
- Uses optionally custom URL when executing requests in server-side.
- Sets default base URL.
- Handles all HTTP exceptions and prevents server side unhandled promise exceptions.
- Injects `$get`,`$post`,... into vue context instances so requests can be done out-of-the-box.
- Exposes `setToken` function so we can easily and globally set authentication tokens.
- Returns empty object if request fails.
- Throws *nuxt-friendly* exceptions if needed.
- 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.
- Automatically enables `withCredentials` when requesting to default base URL.
#### 💡 Usage
## Setup
- Add `@nuxtjs/axios` dependency using yarn or npm to your project
- Add `@nuxtjs/axios` module to `nuxt.config.js`:
```js
modules: [
'@nuxtjs/axios'
]
````
- Add `axios` module
## Usage
### Inside `asyncData`
```js
import {$get} from '~/nuxt-modules/axios';
async data() {
let {profile} = await $get('profile');
return {profile}
async asyncData({app: {$axios}}) {
const {data} = await $axios.get('http://icanhazip.com')
return {
ip: data
}
}
```
Or In any other function: (This does not needs importing axios plugin)
### Inside component methods
```js
mounted() {
let {profile} = await this.$get('profile');
return {profile}
async mounted() {
const {data} = await this.$get('http://icanhazip.com')
this.ip = data
}
```
**Customization**
## Customization

@@ -36,0 +42,0 @@ Customization can be done using shared environment variables.

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