Skip to content
This repository has been archived by the owner on Feb 2, 2021. It is now read-only.

Example of using nuxt & adonis api with Auth api Middleware #32

Closed
cawa-93 opened this issue Mar 16, 2017 · 8 comments
Closed

Example of using nuxt & adonis api with Auth api Middleware #32

cawa-93 opened this issue Mar 16, 2017 · 8 comments

Comments

@cawa-93
Copy link

cawa-93 commented Mar 16, 2017

Earlier you provided an example of appealing to the api. But there is a difficulty: to access the api point you need to be authorized.

Route.group('api', () => {
  Route.resource('users', 'UsersController')
  Route.resource('pages', 'PagesController')
})
.middleware('auth')

On the client side, everything works, but on the server side - I get an error

<template>
<div>{{users}}</div>
</template>

<script>
import axios from '~plugins/axios'

export default {
  async data ({error, req}) {
    const { data } = await axios.get('/api/v1/users.json')
    return {
      users: data
    }
  },
  // async mounted () {
  //  const { data } = await axios.get('api/v1/users.json')
  //  this.users = data
  // }
}
</script>
This question is available on Nuxt.js community (#c30)
@Atinux
Copy link
Member

Atinux commented Mar 16, 2017

Hi @cawa-93

What session provider do your use to authorise the user?

If it's the cookies, you might need to give the cookies of the use you get from req.headers.cookie.

See axios/axios#560 (comment) which might help.

@cawa-93
Copy link
Author

cawa-93 commented Mar 17, 2017

@Atinux, Thanks! The following code work:

import axios from '~plugins/axios'

export default {
  async data ({error, req}) {
    let options = {}
    if (req && req.headers) {
      options.headers = req.headers
    }
    const { data } = await axios.get('/api/v1/users.json', options)
    return {
      users: data
    }
  }
}

But here's the question: is it possible to somehow write this code:

if (req && req.headers) {
  options.headers = req.headers
}

in the plugin /resources/plugins/axios.js, so as not to duplicate it for each page? In other words, how to access the request object inside the plugin

import axios from 'axios'

let options = {}
// The server-side needs a full url to works
if (process.SERVER_BUILD) {
	options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`
	options.headers = req.headers // req = undefined
}

export default axios.create(options)

@Atinux
Copy link
Member

Atinux commented Mar 17, 2017

@cawa-93 it's not possible to access req in the plugin directly, but you can do something like this:

plugins/axios.js

import axios from 'axios'

export default function (req) {
  let options = {}
  // The server-side needs a full url to works
  if (process.SERVER_BUILD) {
    options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`
    options.headers = req.headers
  }
  return axios.create(options)
}

And then, in your page components:

import axios from '~plugins/axios'

export default {
  async data ({error, req}) {
    const { data } = await axios(req).get('/api/v1/users.json')
    return {
      users: data
    }
  }
}

You can also give the full context, but I believe req is the only one you really need for axios.

@Atinux Atinux closed this as completed Mar 17, 2017
@lmj0011
Copy link
Contributor

lmj0011 commented Apr 6, 2017

#32 (comment)

cool, this works. Now I can refresh the page and not get that dreaded Login Error

but if you're prepending your URLs (ie. options.baseURL = '/api/v1'), you will need to do this:

plugins/axios.js

import axios from 'axios'

export default function (req) {
  let options = {}
  options.headers = {}

  // The server-side needs a full url to works
  if (process.SERVER_BUILD) {
    options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}/api/v1`
    options.headers = req.headers
  } else {
    // for when navigating around pages client-side (ie. not server rendering)
    options.baseURL = '/api/v1'
  }
  return axios.create(options)
}

to be able to navigate within the app

@abelmq
Copy link

abelmq commented Sep 5, 2017

Please, I have tried to follow the recommended steps, however I have an error when configuring

import axios from '~ plugins / axios'

This dependency was not found:

* ~plugins/axios in ./node_modules/babel-loader/lib? ...

To install it, you can run: npm install --save ~plugins/axios

in spite of having configured in /config/nuxt.js

build: {
    vendor: ['axios']
  },
  plugins: ['~plugins/axios.js'],

What is missing?

@Atinux
Copy link
Member

Atinux commented Sep 6, 2017

@abelmq ~plugins does not work anymore, use ~/plugins/axios

@abelmq
Copy link

abelmq commented Sep 6, 2017

@Atinux is correct! Thank you very much.

@alanaasmaa
Copy link

alanaasmaa commented Sep 16, 2017

@Atinux Hi, i dont understand at all that async part of data.

How and where can i use this. Where does the error and req param come from. Which framework defines them. Google is not a mate in these stuff. I can't find anything on any documentation.

  async data ({error, req}) {
    const { data } = await axios(req).get('/api/v1/users.')
    return {
      users: data
    }
  }

I cannot use {{ users }} in my template, why is that so ?

How is this different with nuxt asyncData method and which one i should use for which case ?

Is it related with this ? https://nuxtjs.org/guide/async-data

Does it have to do something with this update v0.10.0 that i cant find any async data in documentation ? https://nuxtjs.org/guide/release-notes/

EDIT: I finally did it. For everyone else, yes async-data is updated so see the docs for new syntax.

  asyncData ({req, error}) {
    return axios(req).get('/api/v1/user')
      .then((res) => {
        return { users: res.data.users }
      })
      .catch((e) => {
        error({ statusCode: 404, message: 'Post not found' })
      })
  },
  data () {
    return {
      users: 'default'
    }
  },

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants