首页 > 解决方案 > nuxtjs apollo-client does not set authorization header

问题描述

I am trying to create a login functionality using nuxtjs with the nuxtjs apollo-module and nodejs in the backend using apollo-server. I would like to pass the token from the frontend (nuxtjs/apollo-client) to the backend (nodejs/apollo-server).


Signin Function (frontend)

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 (frontend)

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

Cookie in Browser DevTools

enter image description here

Index File (backend)

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

The token is saved in a cookie called 'apollo-token'. However the Authoriation header in the format 'Bearer token' is not set. According to the apollo-client documentation this should be set automatically (https://github.com/nuxt-community/apollo-module#authenticationtype-string-optional-default-bearer).

What am I missing? I would be very thankful for any kind of help!

标签: node.jsauthorizationnuxt.jsapolloapollo-client

解决方案


推荐阅读