如何在login.vue中添加headers?

How to add headers in login.vue?

如何更新 header 的 apolloProvider?

请查看 nativescript-vue 应用回购:

https://github.com/kaanguru/vue-apollo-login

我无法正确解释,所以请检查应用程序。 我不知道如何更新 appolloClient headers.

App repo 有自己的评论和指令。安装简单,自己看。

当前代码结构:

Post 请求提交用户标识符和密码凭据进行身份验证,并在登录页面获取令牌

Apollo 需要将 jwt 令牌放入授权 header。


import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo'

Vue.use(VueApollo)

const apolloClient = new ApolloClient({
  uri: 'http://sebapi.com/graphql',

// HEADERS WORK FINE IF TOKEN WAS IN MAIN
//   headers: {
//     authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTg2MzU2NzM2LCJleHAiOjE1ODg5NDg3MzZ9.wpyhPTWuqxrDgezDXJqIOaAIaocpM8Ehd3BhQUWKK5Q`,
// }

})
const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

LOGIN.VUE

.then(
          (response) => {
            const result = response.content.toJSON();
            console.log("Result from Server: ", result);
            const token = result.jwt;

            // HOW TO ADD HEADERS TO APOLLOCLIENT this.$apollo.provider.defaultClient

            // this.$apollo.provider.defaultClient({
            //   request: (operation) => {
            //     operation.setContext({
            //       headers: {
            //         authorization: `Bearer ${result.jwt}` ,
            //       },
            //     });
            //   },
            // });

          },

感谢您的关注。

注意:请发表评论以了解更多详情。 sebapi.com 后端是一个 strapi graphql 服务器。

相关文档:

Apollo authentication

Apollo link composition

Vue apolloProvider Usage

问题是您需要使用 ApolloLink 才能将其用于所有请求。你用的方法不行。

你必须使用中间件 apollo-link-context 来实现这个。

根据Apollo-link-context docs

apollo-link-context: Used to set a context on your operation, which is used by other links further down the chain.

The setContext function takes a function that returns either an object or a promise that returns an object to set the new context of a request. Add the below code to app.js and modify some changes and check.

import { setContext } from 'apollo-link-context'

const authLink = setContext((_, { headers }) => {
    // get the authentication token from ApplicationSettings if it exists
    const token = ApplicationSettings.getString("token");

    // return the headers to the context so HTTP link can read them
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : null
        }
    }
})

// update apollo client as below
const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache() // If you want to use then 
})

Login.vue

的变化
.then(
    (response) => {
    const result = response.content.toJSON();
    console.log("Result from Server: ", result);
    const token = result.jwt;
    // Set token using setString
    ApplicationSettings.setString("token", result.jwt);
},

希望对您有所帮助!