【问题标题】:how to set baseUrl in nuxt/axios?如何在 nuxt/axios 中设置 baseUrl?
【发布时间】:2020-01-21 05:35:46
【问题描述】:

在 nuxt axios mudule 中未设置 baseURL,我无法使用 nxut/auth 模块进行身份验证。

这是 nuxt.config.js:

 auth: {
        strategies: {
            local: {
                endpoints: {
                    login: {url: 'auth/login', method: 'post', propertyName: 'data.access_token'},
                    user: {url: 'user', method: 'get', propertyName: 'data'},
                    logout: {url: 'auth/logout', method: 'post'}
                },
                tokenRequired: true,
                tokenType: 'Bearer',
            },
            redirect: {
                home: '/',
                login: '/login',
                logout: '/logout'
            }
        }
    },


 axios: {
        baseURL: "api.dvl/api/v1/"
    },

一切正常,但如果我提出请求,它会请求http://localhost:3000/auth/login

怎么了?

我的登录页面:

 data() {
            return {
                title: process.env.title.fa,
                form: {
                    email: null,
                    password: null,
                    remember: false
                }
            }
        },
        methods: {
            async login() {
                await this.$axios.$post('/login', this.form)
                this.$auth.login({ data: this.form })
            }
        }

【问题讨论】:

    标签: vue.js authentication axios nuxt.js


    【解决方案1】:

    您的异步登录错误。试试下面的代码:

     methods: {
        async login() {
          await this.$auth.loginWith('local', {
            data: {
              email: this.email,
              password: this.password
            }
          })
          this.checkLogin()
        },
    
        checkLogin() {
          console.log(this.$auth.user)
        }
      }
    

    【讨论】:

    • 请分享一些解释,以便其他人可以从您的答案中学习 - 究竟出了什么问题,您的代码有何不同?
    • 你已经使用了 nuxt-auth 模块并在 nuxt 配置中设置了本地策略。因此,对于登录,您必须使用 $auth.loginwith('local', data)。
    【解决方案2】:

    因为在客户端请求 axios 不能使用环境变量然后 您应该在 nuxt 配置中使用 axios 的运行时配置 试试这个:

    export default {
      modules: [
        '@nuxtjs/axios'
      ],
    
      axios: {
        baseURL: 'http://localhost:4000', // Used as fallback if no runtime config is provided
      },
    
      publicRuntimeConfig: {
        axios: {
          browserBaseURL: process.env.BASE_URL
        }
      },
    
      privateRuntimeConfig: {
        axios: {
          baseURL: process.env.BASE_URL
        }
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2019-07-13
      • 2023-01-07
      • 2020-09-17
      • 2022-08-23
      • 1970-01-01
      相关资源
      最近更新 更多