如何在NuxtJS中使用axios添加全局拦截器?

问题描述 投票:0回答:1

我正在使用NuxtJS。所以我想阅读一些响应头并将其保存在VueJS存储中。我看到了以下文档:https://axios.nuxtjs.org/extend.html。据说,我可以添加一些axios插件来处理请求,响应...这是nuxt站点上建议的配置:nuxt.config.js

{
  modules: [
    '@nuxtjs/axios',
  ],

  plugins: [
    '~/plugins/axios'
  ]
}

问题1:为什么未将插件声明为〜/ plugins / axios.js? 〜/ plugins / axios有什么区别吗?为了避免错误,将出现以下错误:

 ERROR  Failed to compile with 1 errors                                        friendly-errors 13:12:58

This dependency was not found:                                                 friendly-errors 13:12:58
                                                                               friendly-errors 13:12:58
* eventsource-polyfill in multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js
                                                                               friendly-errors 13:12:58
To install it, you can run: npm install --save eventsource-polyfill  

我写:

plugins: [
        '~/plugins/axios.js'
      ]

在plugins / axios.js中编写以下代码拦截器:

export default function ({ $axios, redirect }) {
   $axios.onRequest(config => {
        console.log('Making request to ' + config.url)
    }),


    $axios.onResponse(response => {
        console.log(" RESPONSE  ####################### ")
    })
}

当我运行我的应用程序并执行一些请求时。我看不到控制台登录。问题2:缺少什么?

然后我检查我的包json:

 {
  "name": "wp-nuxt",
  "version": "1.0.0",
  "description": "Headless WordPress with Nuxt",
  "author": "Me",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.10.2",
    "nuxt": "^2.0.0"
  },
  "devDependencies": {
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.0"
  }
}

问题3:为什么我在nuxt模块内部没有axios模块?

问题4:如何在nuxt节点模块下安装axios?

谢谢您的帮助。

axios nuxt.js interceptor
1个回答
0
投票

nuxt.config.js:

module.exports = {
  modules: [
   '@nuxtjs/axios',
  ],

  axios: {
    // proxyHeaders: false
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.