如何向 vue-apollo 请求添加 cookie?

How to add cookies to vue-apollo request?

我使用 vue-cli-plugin-apollo,我想通过 cookie 将用户选择的 language 从前端发送到后端。

作为vue-apollo.js我使用下一个模板

import Vue from 'vue'
import VueApollo from 'vue-apollo'
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'

// Install the vue plugin
Vue.use(VueApollo)

// Name of the localStorage item
const AUTH_TOKEN = 'apollo-token'

// Http endpoint
const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || 'http://localhost:4000/graphql'

// Files URL root
export const filesRoot = process.env.VUE_APP_FILES_ROOT || httpEndpoint.substr(0, httpEndpoint.indexOf('/graphql'))

Vue.prototype.$filesRoot = filesRoot

// Config
const defaultOptions = {
  // You can use `https` for secure connection (recommended in production)
  httpEndpoint,
  // You can use `wss` for secure connection (recommended in production)
  // Use `null` to disable subscriptions
  wsEndpoint: process.env.VUE_APP_GRAPHQL_WS || 'ws://localhost:4000/graphql',
  // LocalStorage token
  tokenName: AUTH_TOKEN,
  // Enable Automatic Query persisting with Apollo Engine
  persisting: false,
  // Use websockets for everything (no HTTP)
  // You need to pass a `wsEndpoint` for this to work
  websocketsOnly: false,
  // Is being rendered on the server?
  ssr: false,

  // Override default apollo link
  // note: don't override httpLink here, specify httpLink options in the
  // httpLinkOptions property of defaultOptions.
  // link: myLink

  // Override default cache
  // cache: myCache

  // Override the way the Authorization header is set
  // getAuth: (tokenName) => ...

  // Additional ApolloClient options
  // apollo: { ... }

  // Client local data (see apollo-link-state)
  // clientState: { resolvers: { ... }, defaults: { ... } }
}

// Call this in the Vue app file
export function createProvider (options = {}) {
  // Create apollo client
  const { apolloClient, wsClient } = createApolloClient({
    ...defaultOptions,
    ...options,
  })
  apolloClient.wsClient = wsClient

  // Create vue apollo provider
  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    defaultOptions: {
      $query: {
        // fetchPolicy: 'cache-and-network',
      },
    },
    errorHandler (error) {
      // eslint-disable-next-line no-console
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
    },
  })

  return apolloProvider
}

摘自 here. All options are shown here.

我在不同的 github 讨论中看到 cookies 必须放在 headers 中,例如 here. Then I found, that apollo-link-http has headers 选项,所以最后我尝试了不同的变体...:[=​​25=]

httpLinkOptions: {
  headers: {

    // Tried something like:
    cookie[s]: 'language=en; path=/;'

    // and something like:
    cookie[s]: {
      language: 'en'
    }
  }
}

但运气不好。

如果是 cookieS,我会收到 Error: Network error: Failed to fetch

cookie 的情况下,请求发送没有问题,但后端没有看到 language cookie。

我使用 Postman 仔细检查了后端,在这种情况下,后端收到手动添加 language cookie 的请求。

有人能帮帮我吗?

找到解决方案。

前端设置

  1. 创建 cookie:
export function languageCookieSet (lang) {
  document.cookie = `language=${lang}; path=/;`
}
  1. httpLinkOptions 添加到 vue-apollo.jsdefaultOptions
const defaultOptions = {
  ...

  httpLinkOptions: {
    credentials: 'include'
  },

  ...

后端设置

作为后端,我使用 Django(当前为 v2.2.7)。

  1. 为了开发我们需要使用django-cors-headers
  2. 我的 development.py 现在看起来像:
from .production import *

CORS_ORIGIN_WHITELIST = (
    'http://localhost:8080',
)
CORS_ALLOW_CREDENTIALS = True

INSTALLED_APPS += ['corsheaders']

MIDDLEWARE.insert(0, 'corsheaders.middleware.CorsMiddleware')
  1. 添加到production.py:
LANGUAGE_COOKIE_NAME = 'language'

LANGUAGE_COOKIE_NAME的默认值是django_language,所以如果适合你,改成

document.cookie = `language=${lang}; path=/;`

document.cookie = `django_language=${lang}; path=/;`
  1. 现在在后端我们可以获得前端语言:
import graphene

from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _

from .views import user_activation__create_email_confirmation

User = get_user_model()

class UserRegister(graphene.Mutation):
    """
    mutation {
      userRegister(email: "test@domain.com", password: "TestPass") {
        msg
      }
    }
    """

    msg = graphene.String()

    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)

    def mutate(self, info, email, password):
        request = info.context

        # Here we get either language from our cookie or from
        # header's "Accept-Language" added by Browser (taken
        # from its settings)
        lang = request.LANGUAGE_CODE
        print('lang:', lang)

        if User.objects.filter(email=email).exists():
            # In our case Django translates this string based
            # on the cookie's value (the same as "request.LANGUAGE_CODE")
            # Details: https://docs.djangoproject.com/en/2.2/topics/i18n/translation/
            msg = _('Email is already taken')
        else:
            msg = _('Activation link has been sent to your email.')

            user = User(email=email)
            user.set_password(password)
            user.save()
            user_activation__create_email_confirmation(info.context, user)

        return UserRegister(msg=msg)

注意:我还没有在生产中测试这些变化,但在生产中我只使用一台服务器,前端和后端位于 nGinx 后面,这是CORS 设置存在于 development.py 而不是 production.py 中的原因。同样在生产中 credentials: 'include' 可能会更改为 credentials: 'same-origin' (即更严格)。