未为asnycData请求执行Nuxtjs Axios onRequest() [英] Nuxtjs Axios onRequest() not executed for asnycData request
问题描述
我已经配置了axios插件onRequest
帮助器,以便在如下所示的API请求上设置Authorization
标头
I have configured axios plugin onRequest
helper to set Authorization
header on API requests like below
1. export default function({ $axios, redirect, app, store }) {
2. $axios.onRequest(config => {
3. var requestURL = config.url;
4. console.log("Making request to " + requestURL);
5. const token = store.state.user.account.token;
6. if (token) {
7. config.headers.common["Authorization"] = `Bearer ${token}`;
8. console.log("Added authorization header");
9. }
10. });
此onRequest
助手在store
中为actions
调用.但是对于页面组件中的asyncData
,调用会一直持续到上面的第2行,但永远不会进入onRequest
函数.
This onRequest
helper get invoked for actions
in store
. But for asyncData
in page component, call reaches till line 2 above but never enters the onRequest
function.
import axios from "axios";
asyncData({ params }) {
console.log("params: " + params);
return axios
.get(`http://localhost:8080/user/id/${params.id}`)
.then(res => {
return { userData: res.data };
})
.catch(e => {
error({ statusCode: 404, message: "User not found" });
});
}
据我了解,所有Axios请求都应通过onRequest
辅助函数传递.我在这里想念什么吗?该如何解决?
As I understand all Axios requests should pass through onRequest
helper function. Am I missing something here? How to fix this?
推荐答案
import axios from 'axios'
时,您没有使用最初指定的axios实例的配置.相反,您使用的是全新的axios实例.
When you import axios from 'axios'
you're not using the configuration for the axios instance that you specified initially. Instead, you're using an entirely new axios instance.
正确的方法是利用Nuxt context
中的$axios
实例.
The correct way would be to leverage the $axios
instance from the Nuxt context
.
asyncData(context) {
await context.$axios...
}
这篇关于未为asnycData请求执行Nuxtjs Axios onRequest()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!