I am trying to fetch some data from user and I need to pass bearer token within call.
async asyncData () {
let response = await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${this.$auth.getToken('local')}`} })
},
But this doesn't work, it always says that $auth is undefined, while within template I can easily output any $auth property...
How can I get bearer token within async?
I am trying to fetch some data from user and I need to pass bearer token within call.
async asyncData () {
let response = await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${this.$auth.getToken('local')}`} })
},
But this doesn't work, it always says that $auth is undefined, while within template I can easily output any $auth property...
How can I get bearer token within async?
Share Improve this question asked Jul 6, 2019 at 14:38 LearnerLearner 7733 gold badges13 silver badges38 bronze badges 3-
Make sure
this
is what you think it is. – Titus Commented Jul 6, 2019 at 14:40 - @Titus Okay this is not usable within async. How can I get a cookie that is set from nuxt/auth module? – Learner Commented Jul 6, 2019 at 15:17
-
You can use
this
in anasync
function. You can set the function's context (whatthis
refers to inside the function) usingbind
orcall
orapply
. Here is an example:someObject.asyncData.call(objectWith$authProp)
– Titus Commented Jul 6, 2019 at 15:42
3 Answers
Reset to default 4@Titus is right that "this" is the issue. You don't have "this" available in asyncData because:
You do NOT have access of the ponent instance through this inside asyncData because it is called before initiating the ponent.
You do have access to "context" however so you can call the auth module using that:
async asyncData (context) {
let response = await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${context.app.$auth.getToken('local')}`} })
},
nuxtjs/Auth docs
However you are still not using asyncData as it should be because you're not returning anything that can be merged with data so you might want to try like this:
async asyncData (context) {
let { response } = await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${context.app.$auth.getToken('local')}`} })
return { token: response }
},
Having said that, I don't really understand why you want to get your token in a ponent. Surely you are better off getting it globally through nuxtServerInit in your store.
Maybe you can try to pass the context (this) , after your call?
E.g:
await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${this.$auth.getToken('local')}`} }),this;
You can use something like that:
async asyncData (app) {
let response = await axios.get('dataURL', {}, { headers: {"Authorization" : `Bearer ${app.$auth.getToken('local')}`} });
},
Here is the documentation, you can learn more about it.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744958861a4603364.html
评论列表(0条)