Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

axios module: failed response resolves promise #87

Closed
uptownhr opened this issue Jul 24, 2017 · 13 comments
Closed

axios module: failed response resolves promise #87

uptownhr opened this issue Jul 24, 2017 · 13 comments

Comments

@uptownhr
Copy link
Contributor

uptownhr commented Jul 24, 2017

Failed response through the proxy resolves instead of a reject when ran from the server.

When returning statuscode 500 with message 'invalid token' from the API, the code below results in user being

{ message: 'Request failed with status code 500', statusCode: 500 }

Expected is that the statusCode is still 500 but

  1. the promise should not resolve and reject
  2. The message is also being lost and converted to Request failed from invalid token

Request Code

try {
      let user = await app.$axios.get('/user/me')
      console.log('res user', user)
      store.dispatch('setCurrentUser', user)

    } catch (e) {
      console.log('wtf', e)
    }
This question is available on Nuxt.js community (#c50)
@uptownhr
Copy link
Contributor Author

I was able to confirm that the proper response was returned when I bypass the proxy

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

Hey. Are you testing with latest master version? What if you manually remove errorhandler's logic?

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

Please upgrade to @nuxtjs/axios:2.3.0 and compare result :)

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

Also i think this would be correct usage:

let user = (await app.$axios.get('/user/me')).data

@uptownhr
Copy link
Contributor Author

awesome. that did fix the issue!

However,

the caught error is now,

TypeError: Cannot read property '500' of undefined
at Object.errorHandler (server-bundle.js:1479:22)
at process._tickCallback (internal/process/next_tick.js:109:7)

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

Would you please send a copy of generated .nuxt/axios.plugin.*.js?

@uptownhr
Copy link
Contributor Author

uptownhr commented Jul 24, 2017

import Axios from 'axios'
import Vue from 'vue'

const axiosPlugin = {
  install() {
    if(Vue.__nuxt_axios_installed__) {
      return
    }
    Vue.__nuxt_axios_installed__ = true

    if (!Vue.prototype.hasOwnProperty('$axios')) {
      Object.defineProperty(Vue.prototype, '$axios', {
        get () {
          return this.$root.$options.$axios
        }
      })
    }

    // Vue Component Mixins
    Vue.mixin({
      methods: {
        // opts
        $request (opts) {
          return this.$axios.request(opts);
        },
        // url, opts
        $get (url, opts) {
          return this.$axios.get(url, opts);
        },
        $delete (url, opts) {
          return this.$axios.delete(url, opts);
        },
        $head (url, opts) {
          return this.$axios.head(url, opts);
        },
        // url, data, opts
        $post (url, data, opts) {
          return this.$axios.post(url, data, opts);
        },
        $put (url, data, opts) {
          return this.$axios.put(url, data, opts);
        },
        $patch (url, data, opts) {
          return this.$axios.patch(url, data, opts);
        }
      }
    })
  }
}

Vue.use(axiosPlugin)

// Sets a common header
function setHeader (name, value, scopes = 'common') {
  if(!Array.isArray(scopes)) {
    scopes = [scopes]
  }
  scopes.forEach(scope => {
    if (!value) {
      delete this.defaults.headers[scope][name];
      return
    }
    this.defaults.headers[scope][name] = value
  })
}

// Set requests token
function setToken (token, type, scopes = 'common') {
    const value = !token ? null : (type ? type + ' ' : '') + token
    this.setHeader('Authorization', value, scopes)
}

const redirectError = {}

// Set appreciate `statusCode` and `message` to error instance
function errorHandler(error) {
  if (error.response) {
    // Error from backend (non 2xx status code)
    // ...Auto redirect on special status codes
    if (redirectError[error.response.status]) {
      this.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 = 500
    error.message = error.message || 'axios error'
  }

  return Promise.reject(error)
}



// Setup BaseURL
const baseURL = process.browser
  ? (process.env.API_URL_BROWSER || '/api')
  : (process.env.API_URL || 'http://667837fe8085:3000/api')

export default (ctx) => {
  const { app, store, req } = ctx

  
  // Default headers 
  const defaultHeaders = (req && req.headers) ? Object.assign({}, req.headers) : {}
  delete defaultHeaders.host
  

  // Create new axios instance
  const axios = Axios.create({
    baseURL,
    defaultHeaders,
  })

  
  // 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
  });
  

  

  // Error handler
  axios.interceptors.response.use(undefined, errorHandler.bind(ctx));

  // Make accessible using *.$axios
  app.$axios = axios
  ctx.$axios = axios
  if (store) {
    store.$axios = axios
  }

  // Token helper for authentication
  axios.setToken = setToken.bind(axios)
  axios.setHeader = setHeader.bind(axios)
}

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

I tought problem would be with new redirectError feature. But it is defined too 😕 Does disable this line fixes problem?

   if (redirectError[error.response.status]) {
      this.redirect(redirectError[error.response.status])
    }

@uptownhr
Copy link
Contributor Author

where should i put this?

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

This line is in .nuxt/axios file you have submitted. Sorry for inconveniences. Trying to guess problem.

@uptownhr
Copy link
Contributor Author

i think that fixed it. now i see the response object.

@pi0
Copy link
Member

pi0 commented Jul 24, 2017

@uptownhr Sorry bothering, but would you please restart dev server if error exists? I can't reproduce it.

@uptownhr
Copy link
Contributor Author

@pi0 you're right. I restarted and still fixed. Sorry, should have rebuilt from scratch after upgrading.

@pi0 pi0 closed this as completed Jul 24, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants