代码之家  ›  专栏  ›  技术社区  ›  Schwesi

nuxtjs apollo client未设置授权头

  •  0
  • Schwesi  · 技术社区  · 5 年前

    我试图创建一个登录功能使用 nuxtjs 和nuxtjs在一起 apollo-module nodejs apollo-server . 我想将令牌从前端(nuxtjs/apollo客户端)传递到后端(nodejs/apollo服务器)。


    Signin函数(前端)

    async signin () {
      const email = this.email
      const password = this.password
      try {
        const res = await this.$apollo.mutate({
          mutation: signIn,
          variables: {
            email,
            password
          }
        }).then(({ data }) => data && data.signIn)
        const token = res.token
        await this.$apolloHelpers.onLogin(token)
        this.$router.push('/feed')
      } catch (err) {
        // Error message
      }
    }
    

    apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'http://localhost:8000/graphql',
        wsEndpoint: 'ws://localhost:8000/graphql',
        authenticationType: 'Bearer',
        httpLinkOptions: {
          credentials: 'include'
        },
      }
    }
    

    浏览器开发工具中的Cookie

    enter image description here

    索引文件(后端)

    const app = express()
    
    const corsConfig = {
      origin: 'http://127.0.0.1:3000',
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
      credentials: true
    }
    
    app.use(cors(corsConfig))
    
    app.use(morgan('dev'))
    
    const getMe = async req => {
      const token = req.headers.authorization // <========
      console.log(token) // returns 'Bearer undefined' 
    
      if (token) {
        try {
          return await jwt.verify(token, process.env.SECRET)
        } catch (e) {
          // Error message
        }
      }
    }
    
    const server = new ApolloServer({
      introspection: true,
      playground: true,
      typeDefs: schema,
      resolvers,
      context: async ({ req }) => {    
        if (req) {
          const me = await getMe(req)
    
          return {
            models,
            me,
            secret: process.env.SECRET,
            loaders: {
              user: new DataLoader(keys =>
                loaders.user.batchUsers(keys, models),
              ),
            },
          }
        }
      },
    })
    
    server.applyMiddleware({
      app,
      path: '/graphql',
      cors: false
    })
    
    const httpServer = http.createServer(app)
    server.installSubscriptionHandlers(httpServer)
    
    const port = process.env.PORT || 8000
    
    sequelize.sync({ force: true }).then(async () => {
      createUsers(new Date())
    
      httpServer.listen({ port }, () => {
        console.log(`Apollo Server on http://localhost:${port}/graphql`)
      })
    })
    

    令牌保存在一个名为“阿波罗令牌”的cookie中。但是,未设置格式为“承载令牌”的创作标头。根据阿波罗客户端文档,这应该是自动设置的(https://github.com/nuxt-community/apollo-module#authenticationtype-字符串(可选默认承载)。

    我错过了什么?我将非常感谢任何帮助!
    0 回复  |  直到 5 年前
    推荐文章