Repository axios-module

altafsayani

altafsayani posted a new bug report

axios-module • 3 days ago

bug onError - Not Returning Error Code

Version

v5.1.0

Reproduction link

https://codesandbox.io/

Steps to reproduce

I am trying to use onError helper as mentioned in documentation (https://axios.nuxtjs.org/helpers) But it is not returning error code. It is simply just returning string message "Network Error"

What is expected ?

Should return error object with status code and status message.

What is actually happening?

Only returning generic error message.

daniel-payne

daniel-payne posted a new question

axios-module • 4 days ago

axios withCredentials not being passed from nuxt.config.js

i had a problem that withCredentials was not being picked up from the nuxt.config.js

  axios: {
    withCredentials: true,
    baseURL: process.env.DATA_API 
  },

so i added an axios plugin with

export default function({ $axios, redirect }) {
  $axios.onRequest(config => {
    config.withCredentials = true

    return config
  })
}

and everything worked for me,
any idea what i was doing wrong?

leonfather

leonfather posted a new question

axios-module • 4 days ago

Double ajax call

Hello i'm using nuxt with axios module and i'm getting double ajax calls for the same call :
screenshot 2018-10-19 at 09 34 01

Any idea ?

movepixels

movepixels posted a new question

axios-module • 9 days ago

Using Axios in another plugin

How do you use $axios inside of another plugin? I have a mounted method that requires an override of the standard vue resource so config looks like:

mounted () {
    this.$upload.on('profile-avatar', {
      url: '/shit',
      extensions: ['jpeg', 'jpg', 'png'],
      http: function _http (data) {
        console.log(data, 'http data')
        this.axios.$post(data.url, data.body, { onUploadProgress: data.progress })
          .then((response) => {
            console.log(response)
          })
          .catch((error) => {
            console.log(error.response, 'error ville')
          })
      }
    })
  },

But $post is not defined, tried every variation this.axios.post, asxios.post, $asios.post, $asios.Post and every possible combination but nothing.

There is a new version of the plugin which require to set the options directly in the plugin (this is a native Vue plugin) so I am trying to get it working in Nuxt.

The script is self installing if Vue is available.

import 'vue';
import '@websanova/vue-upload';

Vue.upload.options.http = function () { ... };
...

Any help to get axios working inside a different plugin would be great or point me in the right direction.

Thanks,

Dave

aalenliang

aalenliang posted a new question

axios-module • 11 days ago

How to get request progress?

I like progress-bar most of the time. But when user upload avatar, i'd like to disable the progress-bar and display a custom animation of progress near the avatar upload box.

I find this issue, and i know i can disable integration by passing { progress: false }:
https://github.com/nuxt-community/axios-module/issues/112

so, how can i get progress of an request?

  1. can i pass something like { onProgress: progress => { /* do sth */ } }
  2. or provide another helper(https://axios.nuxtjs.org/helpers) method like onProgress(progress)

I manage to get the progress by using

computed: {
  progress: function() {
    return this.$nuxt.$loading.get()
  }
}

but there are still two problems:

  1. the progress get to 100% very soon, while my uploading request last about 5 seconds.
    which results my progress bar is 100%, but i can't get my new avatar image until 5 seconds later. very strange?
  2. i can't get the progress with { progress: false } option, so i can't display my progress-bar with the default progress-bar disabled.
tiagomatosweb

tiagomatosweb posted a new question

axios-module • 13 days ago

axios collection

Hi all,
Before getting to use axios module I used to make an axios collection with is pretty much and independent API ajax layer like so

me.js

import axios from 'axios';

export default {
    getMyDetails() {
        const url = 'me';
        return axios.get(url).then(response => response.data);
    },
   ...
};

index.js

import me from './me';

export {
    me,
};

So I usually boot this file with webpack (apiUrl) so that it becomes a global constant, then I can use anywhere for example
apiUrl.me.getMyDetails();

Since I have swap to axios module I do not have access to $axios instance outside of Nuxt.

Any idea to keep similar approach using the $axios instance?

I could create plugin, but I don't know how to separate files by entity (Me, Job, Auth) then import all into a single Nuxt plugin file.

Not sure if I was clear enough… :/

Cheers.

megapctr

megapctr posted a new question

axios-module • 13 days ago

Failed requests break SSR even if they are handled

I have a nuxt app with a onResponseError handler for handling exceptions.

The handler works great in client mode:
rendered page with an alert

But in server mode (SSR) the entire render breaks if a request fails:
generic nuxt error page

…even though my handler is being called correctly in SSR:
server log showing the handler works

I think that SSR should render a page with the alert, just like in the client mode. Am I doing something wrong?

mydesireiscoma

mydesireiscoma resolved the question #c169

axios-module • 14 days ago

How to send cookies from the client side to the backend ?

Solved using @nuxtjs/proxy

In nuxt.config.js

  // ...
  axios: {
    proxy: true,
    baseURL: 'https://mylocalhost.dev2/api'
  },
  proxy: {
    '/api': {
      target: 'https://mylocalhost.dev2',
      secure: false
    }
  },
  // ...

Somewhere in your app

// ...
await $axios.get(`/api/resources/${params.resource}/products/search` + queryString)
// ...
mydesireiscoma

mydesireiscoma posted a new question

axios-module • 14 days ago

How to send cookies from the client side to the backend ?

I have an NuxtJS application (client.local host)
and backend (Laravel) (api.local host)

I have the following line in the asyncData:
const response = await $axios.get(resources/${params.resource}/products/search+ queryString)

My application works in SPA + SSR mode.

I have two pages:

  • Main page
  • Search results page

On the client side I manually set dummy cookie (let's say, by pressing a button)
The search results page makes an ajax request to the api.local in the asyncData

When I went to url http://client.local/search?query=box manually (i.e. page rendered on the server side), requests includes cookies what was set on the client side.
But when I do it it in following way:

  • Go to the main page
  • Enter something in the search input
  • Submit
  • Page chaged to Search results
    i.e. application works in spa mode, i.e. page are rendered on the client side
    cookies are not sent. They exists (checked by document.cookie), but not sent

Please note: cookies are sending, but only when page is rendered on the server side.

So, my question is: how to send cookies to the backend when I do $axios.get, while application works in SPA mode?

alexstaroselsky

alexstaroselsky posted a new question

axios-module • 14 days ago

nuxtServerInit $get() JSON parsing Issue

Attempting to make the following $get in nuxtServerInit method of a classic mode Vuex store of a Nuxt application is yielding a non JSON return type.

import Vuex from "vuex";

const createStore = () => {
  return new Vuex.Store({
    state: () => ({
      todo: null
    }),
    mutations: {
      receiveTodo(state, todo) {
        state.todo = todo;
      }
    },
    actions: {
      async nuxtServerInit({ commit }, { app }) {
        const todo = await app.$axios.$get("https://jsonplaceholder.typicode.com/todos/1");
        console.log(todo);
        commit("receiveTodo", todo);
      }
    }
  });
};

export default createStore;

The value of console.log(todo) is coming back as:

��\u0002\u0000 �o;�лϓt`\tv� �j��\u0003�j��\u0003~;$tp��JP����6\b�SAs�B�\u0004N��vy�a�e��ᰱ��\u0007

Instead of JSON:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

What would need to be done in terms of Nuxt configuration or the call itself to extract the JSON returned from an HTTP GET to https://jsonplaceholder.typicode.com/todos/1? Does something like fetch() method json() need to be executed against the response? Or does a header of Accept: application/json need to be set? If so, how can the header be set for this specific $get()?

With debug set to true in the axios options, the following is logged additionally:

[Axios] [200 OK] [GET] https://jsonplaceholder.typicode.com/todos/1

Executing the same call app.$axios.$get("https://jsonplaceholder.typicode.com/todos/1") in a component within the asyncData() method successfully returns JSON. It seems to be a possible parsing issue when executing in nuxtServerInit().

This application was created using create-nuxt-app and uses "nuxt": "^2.1.0" and "@nuxtjs/axios": "^5.3.3".

Thank you for any help you can provide.

chrisleyva

chrisleyva resolved the question #c166

axios-module • 21 days ago

How can I use nuxt axios module in server/api routes?

Sorry, I wasn't really thinking clearly when I posted this. It's not possible for client and server to share the same instance of an object. The app is running in two different environments (one on my AWS instance and the other in the User's browser).

Plus, I don't really want to share the nuxt axios' config object with the server axios instance. Thanks

monopolly

monopolly posted a new question

axios-module • 24 days ago

Failed to load resource: The network connection was lost.

I'm new in Nuxt and I can't understand this problem.

Sometimes I got a 500 from axios. Its work fine from localhost everytime. API server work good always no any errors
but axios return status 500 time to time.

I make a request
async asyncData({params, error, app}) {
let id = params.id
const data = await app.$axios.$post('/api',{name:'get', body: {id}})
return {data}
}

here is a config, I setup 5 but still status 500
axios: {
proxy: true,
debug: true,
retry: { retries: 5 }
},

I deploy nuxt as univeral in docker. And Docker works fine on localhost with remote api server
No logs, no errors from nuxt or axios or any… Just 500
Whats I make wrong?

In browser

[Axios] – "Response error:"
Error: Network Error
exports — vendor.368959007ad5dc97bb88.js:2:111857
onerror — vendor.368959007ad5dc97bb88.js:2:91841

Failed to load resource: The network connection was lost.

Its not an API server. What is this? Docker? Proxy? Axios?

hardikshah91

hardikshah91 resolved the question #c143

axios-module • 24 days ago

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

fixed

chrisleyva

chrisleyva posted a new question

axios-module • a month ago

How can I use nuxt axios module in server/api routes?

In the nuxt app, we can use the axios module in either of the following ways:

// `app` or `this` depending on the context (server / client)
app.$axios.$get('http://icanhazip.com')
this.$axios.$get('http://icanhazip.com')

But I have an express server in my nuxt app. I'd like to use the same $axios instance in the express routes .js files.

I have both of these files: server\index.js and server\api\user.js.

In my user.js file, I use const axios = require('axios') and it works but I'm not sure if this will have access to the baseUrl and browserBaseUrl I define in my nuxt.config.js.

Thank you for your help.

tonysworking

tonysworking posted a new question

axios-module • a month ago

Possible CORS error, Postman Calls work to API but Store-> Actions-> Axios Calls to LOGIN do not work BCRYPT compare password fails.

This is a general NUXT question.

I am making an axios request to login a user, I can sign-up a user with no errors, but when i try to login, that newly made user with axios does not work, I get a 401 error

If i use postman to Create a user and Log in that same user It works perfectly.

If i use postman to login the user created with Axios it gives a 401 error.

is nuxt sending a different type of data to the server because I am converting a vueJS app to a nuxtApp and the VUEJS app works perfectly as well.

the API is its own app and runs on an entirely different port (2030) and has nothing todo with the Nuxt application, it has CORS set up in the app

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');

    return res.status(200).json({});
}
next();

});

the failed code is as such:

API LOGIN

USER LOGIN
router.post('/login', (req, res, next) => {
console.log('request');
User.findOne({
email: req.body.email
})
.exec()

    .then(user => {
        if (user.length < 1) {
            return res.status(401).json({
                message: 'Authorization Failed'
            });
        }

    bcrypt.compare(req.body.password, user.password, (err, result) => {

            if (err) {
                return res.status(401).json({
                    message: err,
                });
            }

            if (result) {
                const token = jwt.sign({
                        email: user.email,
                        userId: user._id,
                    },
                    process.env.JWT_KEY, {
                        expiresIn: '1h'
                    });
                return res.status(200).json({
                    message: user,
                    token: token
                });
            }
            res.status(401).json({
                message: err,
            });
        });

    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });

})

The Nuxt Store Action:

login({
commit,
state
}, authData) {
axios
.post("http://127.0.0.1:2030/users/login", {
email: authData.email,
password: authData.password,
returnSecureToken: true
})
.then(res => {
commit("authUser", {
token: res.data.token
});
state.userIncorrectLogin = "";
router.push("/dashboard");
})
.catch(error => {
state.userIncorrectLogin =
"Email Or Password is Incorrect Please try again or Reset Password";
});
},

The login.vue Methods:

methods: {
submit(email, password) {
this.$validator.validateAll();
if (!this.errors.any()) {
this.$store.dispatch("login", { email, password });
}
},

Any thoughts or recommendations on this issue.

Thanks in Advance.

arminmon

arminmon posted a new question

axios-module • a month ago

axios default params in nuxt.config

Is there any way to set default params for get requests using axios in nuxt.config.js?
Maybe an Object like this:
axios: {
params: {
'apikey': givenApiKey 'memberkey: givenMemberKey
}
}
The only workaround I found was to create an axios plugin and use "axios.defaults.params" which is unpractical for my use case.

sweetim

sweetim posted a new question

axios-module • a month ago

v5.3.1 has no typings

The latest version from npm has no typings?

sinoru

sinoru posted a new bug report

axios-module • a month ago

bug Return type of $methods in Type Definition is wrong

Version

eca7298

Reproduction link

https://github.com/nuxt-community/axios-module/pull/143

Steps to reproduce

Using $methods(i.e: $post, $get) in TypeScript projects.

What is expected ?

Just works.

What is actually happening?

Return wrong type which is AxiosPromise<T>, which resolved as AxiosResponse<T>.
But $method returns AxiosResponse<T>.data as-is. So It should be just Promise<T>

saratitan

saratitan posted a new question

axios-module • 2 months ago

Use other domain as base URL but override certain paths with proxy

Even with proxy enabled, I'm unable to override certain paths. I have the following code:

  axios: {
    proxy: true,
    browserBaseURL: "http://some-api.com"
  },
  proxy: {
    "/content/": { target: "http://localhost:8000", pathRewrite: { "^/content/": "" } },
  }

This will make a request to http://some-api.com/content when it should make a request to http://localhost:8000/
Changing browserBaseURL to just baseURL will make every request go to itself (http://localhost:3000) except for /content which will go to :8000 as intended.

ealves-pt

ealves-pt posted a new bug report

axios-module • 2 months ago

bug proxyHeadersIgnore not working

Version

v5.1.0

Reproduction link

https://jsfiddle.net/9d3cksm7/

Steps to reproduce

-

What is expected ?

Headers cf-ray and cf-connecting-ip should be removed.

What is actually happening?

Headers cf-ray and cf-connecting-ip are still present in the proxyReq.

Additional comments?

I have the following nuxt.confg.js:

require('dotenv').config()

module.exports = {
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    },
    postcss: {
      plugins: {
        'postcss-custom-properties': {
          warnings: false
        }
      }
    }
  },
  /*
  ** CSS dependencies
  */
  css: [
    'bulma',
    '@/assets/sass/main.scss'
  ],
  /*
  ** Headers of the page
  */
  head: {
    title: 'Test',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Test' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress bar color
  */
  loading: { color: '#3B8070' },
  /*
  ** Nuxt.js extensions
  */
  modules: [
    [
      '@nuxtjs/proxy',
      {
        onProxyReq (proxyReq, req, res) {
          console.log(proxyReq)
        }
      }
    ],
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    '@nuxtjs/dotenv',
    [ '@nuxtjs/google-tag-manager', { id: 'GTM-XXXXXXX' } ]
  ],
  /*
  ** Extend auto-generated routes
  */
  plugins: [
    '~/plugins/axios'
  ],
  /*
  ** Extend auto-generated routes
  */
  router: {
    middleware: [ 'auth' ]
  },
  /*
  ** @nuxtjs/options Options
  */
  axios: {
    proxy: true,
    proxyHeadersIgnore: ['host', 'accept', 'cf-ray', 'cf-connecting-ip']
  },
  proxy: {
    '/api/': { target: process.env.API_ENDPOINT, pathRewrite: { '^/api/': '' } }
  },
  /*
  ** @nuxtjs/auth Options
  */
  auth: {
    redirect: {
      login: '/auth/login',
      logout: '/auth/login',
      user: '/'
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/v1/authentication', propertyName: 'accessToken' },
          user: { url: '/api/v1/me', propertyName: 'email' },
          logout: false
        }
      }
    },
    tokenRequired: true,
    fullPathRedirect: true
  }
}

The proxyIgnoreHeaders are being ignored because the onProxyReq still shows them and also because cloudflare is showing me the Error: 1000.

My package.json is the following:

{
  "name": "some-ui",
  "version": "1.0.0",
  "description": "Test",
  "author": "",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "precommit": "npm run lint"
  },
  "dependencies": {
    "@nuxtjs/auth": "^4.5.1",
    "@nuxtjs/axios": "^5.3.1",
    "@nuxtjs/dotenv": "^1.1.1",
    "@nuxtjs/google-tag-manager": "^1.1.0",
    "bulma": "^0.7.0",
    "clipboard": "^2.0.0",
    "ibantools": "^2.0.0",
    "isemail": "^3.1.2",
    "jsvat": "^1.2.3",
    "nuxt": "^1.4.2",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "babel-eslint": "^8.2.6",
    "eslint": "^4.15.0",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-vue": "^4.7.1",
    "node-sass": "^4.9.3",
    "sass-loader": "^7.1.0"
  }
}

Can anyone help me with this please?