nuxtjs apollo-client未设置授权标头

时间:2020-09-13 11:59:37

标签: node.js authorization nuxt.js apollo apollo-client

我正在尝试使用nuxtjs和nuxtjs apollo-modulenodejs在后端使用apollo-server创建登录功能。我想将令牌从前端(nuxtjs / apollo-client)传递到后端(nodejs / apollo-server)。


登录功能(前端)

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
  }
}

nuxtjs.config(前端)

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`)
  })
})

令牌保存在名为“ apollo-token”的cookie中。但是,未设置“承载者令牌”格式的授权标头。根据apollo-client文档,应该自动设置(https://github.com/nuxt-community/apollo-module#authenticationtype-string-optional-default-bearer)。

我想念什么?我将非常感谢您提供的任何帮助!

0 个答案:

没有答案