问题
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. });
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" });
});
}
As I understand all Axios requests should pass through onRequest
helper function. Am I missing something here? How to fix this?
回答1:
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.
The correct way would be to leverage the $axios
instance from the Nuxt context
.
asyncData(context) {
await context.$axios...
}
回答2:
You can also use the $axios
instance directly. An example is:
asyncData({$axios}) {
await $axios...
}
来源:https://stackoverflow.com/questions/59807124/nuxtjs-axios-onrequest-not-executed-for-asnycdata-request