Как добавить куки в запрос vue-apollo? - PullRequest
0 голосов
/ 26 октября 2019

Я использую vue-cli-plugin-apollo , и я хочу отправить language выбранный пользователем из внешнего интерфейса в бэкэнд через cookie.

Как 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
}

взят из здесь . Здесь показаны все варианты здесь .

В различных обсуждениях github я видел, что cookies должен быть помещен внутри headers, например здесь . Затем я обнаружил, что apollo-link-http имеет заголовки , поэтому в конце я попробовал различные варианты ...:

httpLinkOptions: {
  headers: {

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

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

, но не повезло.

В случае печенья S я получаю Error: Network error: Failed to fetch.

В случае cookie запрос отправляется без проблем, но бэкэнд не видит language cookie.

Я дважды проверил бэкэнд, используя Postman, и в этом случае бэкэнд получаетзапрос с добавленным вручную language cookie.

Может ли кто-нибудь мне помочь?

1 Ответ

0 голосов
/ 26 октября 2019

Найденное решение.

НАСТРОЙКИ ПЕРЕДНЕГО КОНЦА

  1. Создать cookie:
export function languageCookieSet (lang) {
  document.cookie = `language=${lang}; path=/;`
}
Добавить httpLinkOptions к defaultOptions из vue-apollo.js.
const defaultOptions = {
  ...

  httpLinkOptions: {
    credentials: 'include'
  },

  ...

НАЗАД НАСТРОЙКИ

В качестве бэкэнда я использую Django(в настоящее время v2.2.7).

  1. Для разработки нам нужно использовать django-cors-headers
  2. My development.py теперь выглядит так:
from .production import *

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

INSTALLED_APPS += ['corsheaders']

MIDDLEWARE.insert(0, 'corsheaders.middleware.CorsMiddleware')
Добавить к production.py:
LANGUAGE_COOKIE_NAME = 'language'

Значение по умолчанию LANGUAGE_COOKIE_NAME равно django_language, поэтому, если оно подходит для вас, измените

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

до

document.cookie = `django_language=${lang}; path=/;`
Теперь в бэкэнде мы можем получить язык интерфейса:
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' (т.е. более строгое).

...