【问题标题】:Why Nuxt making multiple request for the "user" endpoint?为什么 Nuxt 向“用户”端点发出多个请求?
【发布时间】:2021-10-14 03:48:02
【问题描述】:

有一个 Express 服务器和一个 Nuxt 客户端。 Nuxt 版本是 2.15.7。

整个auth配置:

// nuxt.config.js
auth: {
  plugins: [
    {
      src: '~/plugins/axios',
      ssr: true
    },
    {
      src: '~/plugins/auth'
    }
  ],
  cookie: {
    prefix: 'auth.',
    options: {
      path: '/',
      secure: process.env.NODE_ENV === 'production' ? true : false
    }
  },
  localStorage: {
    prefix: 'auth.'
  },
  vuex: {
    namespace: 'auth'
  },
  strategies: {
    local: {
      scheme: 'refresh',
      token: {
        property: 'accessToken',
        maxAge: 900,
        global: true,
        name: 'Authorization',
        type: 'Bearer'
      },
      refreshToken: {
        property: 'refreshToken',
        data: 'refreshToken',
        maxAge: 5184000
      },
      user: {
        property: 'user',
        autoFetch: false
      },
      endpoints: {
        login: {
          url: '/user/sign_in',
          method: 'post'
        },
        logout: {
          url: '/user/sign_out',
          method: 'delete'
        },
        refresh: {
          url: '/user/refresh',
          method: 'get'
        },
        user: {
          url: '/user/profile',
          method: 'get'
        }
      }
    }
  },
  redirect: {
    login: '/auth/sign_in',
    logout: '/',
    callback: '/auth/sign_in',
    home: '/'
  }
}

当我在浏览器中刷新页面时,我在浏览器日志中看到:

这条消息来自这里:

// plugins/axios.ts
import { AxiosRequestConfig } from 'axios'

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

服务器日志中还有两个请求。但是在第一个请求中,我可以获得例如 cookie,而在第二个请求中,我可以得到:

// console.log(req.cookies)

[Object: null prototype] {}

你能告诉我为什么会有两个请求吗?

【问题讨论】:

  • 您确定它们是请求,而不仅仅是记录了两次的同一个请求吗?检查网络选项卡。
  • @BrahmaDev 我在服务器日志中看到两个请求。主要问题是第二个请求会导致服务器出错,因为服务器看不到 cookie。在第一个请求中,服务器会看到所有 cookie,但在第二个请求中却没有。
  • 这2个请求的状态码是什么?您确定这不是 CORS 问题吗?
  • 否则,如果您到达 URL(而不是通过客户端导航),如果您的 target 设置为 server(默认值),那么您确实有双重获取是合法的.如果您想禁用此行为nuxtjs.org/docs/2.x/components-glossary/pages-fetch#options,您始终可以将fetchOnServer 设置为false
  • @kissu first - 204, second - 200. 我不相信问题是 CORS ????

标签: javascript vue.js vuejs2 axios nuxt.js


【解决方案1】:

问题是登录后后台返回这个问题造成的:

{
  "is": 1
}

并且应该返回这个:

{
  "user": {
    "is": 1
  }
}

?

添加“用户”对象后,nuxt auth 接受了信息并开始正常工作。

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多