Activities

napestershine

napestershine resolved the question #c348

axios-module •

Access API with basic auth

Solved

napestershine

napestershine posted a new question

axios-module •

Access API with basic auth

HI

I need to make request to an API which need HTTP Basic auth to bypass. I tried it many ways to access it but no luck for now.

I tried to setup in nuxt.config.js

 axios: {
    host: 'http://example.com',
    credentials: {
      username: process.env.API_USER,
      password: process.env.API_PASSWORD
    },
    debug: true,
    https: false
  }

But it doesn't work.

so I tried to put it directly:

<script>
export default {
  async asyncData({ $axios, error }) {
    try {
      const { data } = await $axios({
        method: 'get',
        url:
          'http://example.com/api/post_categories.json',
        withCredentials: true,
        headers:{Authorization:'Basic '+BASE64ENCODED(USERNAME+':'+PASSWORD)}
      })
      return {
        categories: data
      }
    } catch (e) {
      // eslint-disable-next-line no-console
      console.log(e)
    }
  }
}
</script>

it's working for single API, but how can I set it up globally through nuxt.config.js

Thanks

jjelev

jjelev posted a new feature request

axios-module •

idea Use globalName instead of window.$nuxt in the plugin

What problem does this feature solve?

Nuxt global is leaking in the final build of application. However many modules reference this directly instead of refering to global name from configuration.

Can we use the globalName option in the nuxt config instead of $nuxt directly ?
https://github.com/nuxt-community/axios-module/blob/dev/lib/plugin.js#L129

const $loading = () => (window.$nuxt && window.$nuxt.$loading && window.$nuxt.$loading.set) ? window.$nuxt.$loading : noopLoading

What does the proposed changes look like?

const $loading = () => (window.<%= options.globalName %> && window.<%= options.globalName %>.$loading && window.<%= options.globalName %>.$loading.set) ? window.<%= options.globalName %>$loading : noopLoading
blowsie

blowsie posted a new question

axios-module •

HTTPS on localhost

HTTPS on localhost is not possible because of this change.
https://github.com/nuxt-community/axios-module/pull/93

There is no justification as to why this change has been made.

To me it feels like a developer issue and what should have been done is something along the lines of this in the config.

 https: process.env.NODE_ENV === 'development',

As it stands at the moments the https setting is redundant in localhost and the limitation is not well documented

sobolevn

sobolevn posted a new bug report

axios-module •

bug Can't resolve 'defu' in '/code/.nuxt'

Version

5.9.5

Reproduction link

https://travis-ci.com/github/wemake-services/wemake-vue-template/jobs/297973346#L1250

Steps to reproduce

  1. Install this template: https://github.com/wemake-services/wemake-vue-template
  2. Install dependencies with npm i
  3. Run npm run build

What is expected ?

I expect everything to work.

What is actually happening?

Nuxt is not building. Here's an output:

ERROR in ./.nuxt/axios.js
Module not found: Error: Can't resolve 'defu' in '/code/.nuxt'
 @ ./.nuxt/axios.js 6:0-24 75:31-35
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi ./.nuxt/client.js
alihamza1214

alihamza1214 posted a new question

axios-module •

Cannot read property 'setToken' of undefined

I just upgraded my nuxt version from 2.8.1 to 2.11.0 and nuxt axios from 5.5.4 to 5.9.5. After upgrading I am getting this error "Cannot read property 'setToken' of undefined" in async nuxtClientInit function.

async nuxtClientInit({ commit, dispatch }, context) {
// Authorization

let auth = this.$cookies.get('Authorization')
if (auth) {
  this.$axios.setToken(auth, 'Bearer')
  try {
    await dispatch('auth/fetch')
    // return true
  }
  catch (error) {
    this.$axios.setToken(null)
    // return false
  }
} else {
  this.$axios.setToken(null)
  // return false
}

}

kyrsquir

kyrsquir posted a new feature request

axios-module •

idea Enable axios to use current page's domain as host for client requests

What problem does this feature solve?

Since nuxt generate can't be used together with nuxt.config.js axios: { proxy: true }, is there a way to configure axios to extract host for browser(client) requests from current browser page domain? If what I'm asking for doesn't make sense please point me to the right direction on where to look for solution. I'm trying to setup a Docker config with nuxt generate which could be run from both local development machine and production without any adjustments and this proxy limitation really prevents me from reaching this without hardcoding stuff.

If described above makes any sense at all consider the following changes:

What does the proposed changes look like?

Perhaps we could use document.location.host to extract host while in the browser and append our port and prefix to it?

This would mean settings in nuxt.config.js like (inspired by proxy setting)

axios: { 
    reuseBrowserDomain: true
},
browserAxios: {
    port: 1337,
    prefix: '/api'
}

which take precedence over browserBaseURL in case they are set.

Another option would be to allow setting a function to browserBaseURL which is to be executed in browser context.

ksromero

ksromero posted a new question

axios-module •

axios property get of undefined?

I have a class inside src/lib/lib.ts

export default class LibClass {
   someFunc () {
       ...
       const httpResponse = await (this as any).$axios.$get(url)
       return httpResponse.data
   }
}

and Im getting TypeError: Cannot read property '$get' of undefined

I already defined the @nuxtjs/axios on tsconfig.json

"types": [
  "@nuxtjs/axios",
]

I used $axios on LibClass to be able to separate my axios calls and just call it on my components using dependency injection (inversify.js)

any idea on how can I fix this?

selfagency

selfagency posted a new bug report

axios-module •

bug Fetch command just doesn't work

Version

v5.9.4

Reproduction link

https://codesandbox.io/s/nuxt-fetch-axios-issue-26lym

Steps to reproduce

  • Create a store module
  • Add an action to the module that invokes an $axios GET request
  • Call that action via mounted() inside a component
  • Get a 200 response
  • Call that action via fetch() inside a component
  • Get a 404 error
  • Inspect the 404 error, and see that http://your_api.url/ is gone from the GET request despite being present inside the $axios config.

What is expected ?

Axios shouldn't be dropping the baseUrl when using fetch()

What is actually happening?

Axios is dropping the baseUrl when using fetch()

  response:
   { status: 404,
     statusText: 'Invalid host',
     headers:
      { 'access-control-allow-origin': '*',
        'access-control-expose-headers': 'access-control-allow-origin',
        date: 'Wed, 04 Mar 2020 19:31:59 GMT',
        connection: 'keep-alive',
        'transfer-encoding': 'chunked' },
     config:
        [...]
        method: 'get',
        baseURL: 'http://localhost:1337/',
        url: 'http://localhost:1337/Pages?slug=home',
        data: undefined },
     request:
         [...]
        _header:
         'GET /Pages?slug=home HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nconnection: keep-alive\r\npragma: no-cache\r\ncache-control: no-cache\r\nupgrade-insecure-requests: 1\r\nuser-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1\r\naccept-encoding: gzip, deflate\r\naccept-language: en-US,en;q=0.9\r\ncookie: i18n_redirected=en; i18n_mb=en\r\nHost: localhost:1337\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/Pages?slug=home',
        [...]
     data: 'Invalid host: pages' } }

Additional comments?

This happens if you use environment variables, a static URL, or the @nuxtjs/proxy module.

yogisaka

yogisaka posted a new question

axios-module •

Proxy, Missing "target" option

nuxt.config.js

axios: {
    debug: true,
    proxy: true
  },
  proxy: {
    '/api/': {
      target: process.env.API_URL,
      pathRewrite: {
        '^/api': ''
      }
    }
  },

im using config like this and give some error

 ERROR  [HPM] Missing "target" option. Example: {target: "http://www.example.org"}                                         12:12:03

  at Object.createConfig (node_modules/http-proxy-middleware/lib/config-factory.js:43:11)
  at new HttpProxyMiddleware (node_modules/http-proxy-middleware/lib/index.js:17:30)
  at module.exports (node_modules/http-proxy-middleware/index.js:4:10)
  at proxy.forEach (node_modules/@nuxtjs/proxy/lib/module.js:63:30)
  at Array.forEach (<anonymous>)
  at ModuleContainer.proxyModule (node_modules/@nuxtjs/proxy/lib/module.js:61:9)
  at ModuleContainer.addModule (node_modules/@nuxt/core/dist/core.js:190:34)
  at ModuleContainer.requireModule (node_modules/@nuxt/core/dist/core.js:133:17)
  at ModuleContainer.axiosModule (node_modules/@nuxtjs/axios/lib/module.js:106:10)
  at ModuleContainer.addModule (node_modules/@nuxt/core/dist/core.js:190:34)

but if im not using process.env.API_URL and replace with direct url its work, how to use process.env. ?

benlutz

benlutz posted a new question

axios-module •

Migrating from axios to nuxt/axios

Hi,

I am a beginner working with nuxt and axiox, but I was able to set up a frontend with nuxt and a backend with node.js. While trying to implement Nuxt Auth I ran into a problem: after installing nuxt/axios the page seems to stop working. Right now - please forgive me if I am mistaken - I feel like the normal axios and nuxt/axios do not properly work together. Is there an easy way to migrate from axios to the axios module of nuxt? How do I remove axios completely and install the axios module?

Thank you very much in advance! I spent so much time trying to figure this out..

who-jonson

who-jonson posted a new question

axios-module •

How to use @nuxtjs/axios module inside serverMiddleware(Express.js)?

I'm using the officially supported axios-module (@nuxtjs/axios). Now how can I use this inside the serverMiddleware? Is this possible?

BTW, I'm using Express.js for Server Middleware.

Thanks in Advance

david8z

david8z posted a new question

axios-module •

PUT or POST requests through Proxy

Is there a way to make PUT or POST requests go through proxies?

this.$axios.get('path') working through proxy bust when changing get by put or post they aren't going through declared proxy.

orhanmusellim

orhanmusellim posted a new question

axios-module •

F5 Refresh return string problem.

I am using asyncData on the page. Open page axios method works well on Nuxt route. Return the object on the API. However, when you refresh the page, the object data returns as a string. I can't use JSON.parse either.
My asyncData codes ;

async asyncData({params, $axios}) { const productDetail = await $axios.$get('/store/products/getsingle/' + params.slug) return {ilanDetail, productDetail} },

Please help me.

orhanmusellim

orhanmusellim posted a new question

axios-module •

F5 Refresh return string problem.

I am using asyncData on the page. Open page axios method works well on Nuxt route. Return the object on the API. However, when you refresh the page, the object data returns as a string. I can't use JSON.parse either.
My asyncData codes ;

async asyncData({params, $axios}) { const productDetail = await $axios.$get('/store/products/getsingle/' + params.slug) return {ilanDetail, productDetail} },

Please help me.

Mariana-Yui

Mariana-Yui posted a new question

axios-module •

asyncData axios 503

when I use $axios.$get in asyncData,

async asyncData({ $axios }) {
        const { list } = await $axios.$get('http://localhost:3000/api/list')
        return { list }
    }

ubuntu terminal always throw error like:

(node:9628) UnhandledPromiseRejectionWarning: Error: Request failed with status code 503
at IncomingMessage.emit (events.js:228:7)
    at IncomingMessage.EventEmitter.emit (domain.js:475:20)
    at endReadableNT (_stream_readable.js:1185:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:21)
(node:9628) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
(node:9628) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

but when I use the terminal in the vscode, error disappeared. I'm confused. :(

cfroe

cfroe posted a new question

axios-module •

5.9.x Internet Explorer 11 throwing errors

Using Nuxt Axios module with 5.9.x Internet Explorer 11 is not working anymore throwing errors 'const' is undefined. 5.8.0 is working

cfroe

cfroe posted a new question

axios-module •

5.9.x Internet Explorer 11

Using Nuxt Axios module with 5.9.x Internet Explorer 11 is not working anymore throwing errors 'const' is undefined. 5.8.0 is working

golubvladimir

golubvladimir posted a new bug report

axios-module •

bug Don't work validateStatus ?

Version

v5.9.5

Reproduction link

https://codesandbox.io/s/hardcore-moon-80gu8

Steps to reproduce

Wran get a response with 402 error, my onError function work, but validateStatus in this case is false.

What is expected ?

Wran get a response with 402 error, my onError function work, but validateStatus in this case is false.

What is actually happening?

Work onResponse method

golubvladimir

golubvladimir posted a new question

axios-module •

How to return result to action, if I retry request in onError ?

I have getMenu action with axios.

export const actions = {
  async getMenu({rootState, commit}) {
    try {
      const { auth, lang } = rootState;

      const {items} = await this.$axios.$get(`/api/${ lang.locale }/menu`, {
        headers: {
          'Authorization': `bearer ${auth.token}`,
          'Accept-Language': `${lang.locale}`
        },
      });

      console.log({'getMenu': items});

      if (items) {
        // set items
        commit('setMenu', items);
      }
    } catch (error) {
      console.log({Error: error})
    }
  }
};

In backend on this route, I have middleware authenticate user.
In case of error, I request new token, after I make a new request.

$axios.onError(async (error) => {
    const code = parseInt(error.response && error.response.status);
    const message = error.response && error.response.data && error.response.data.error;

      if (code === 403) {
        await store.dispatch(
          'auth/refreshToken',
          { refreshToken: store.state.auth.refreshToken },
          { root: true }
        );

        const method = error.config.method;
        const url = error.config.url;
        const token = store.state.auth.token;
        const locale = store.state.lang.locale;

        if (method === 'get') {
          return await $axios.$get(url, {
            headers: {
              'Authorization': `bearer ${ token }`,
              'Accept-Language': `${ locale }`
            }
          });
        }
      }

How to return resut to initial action ?